如果为空,我需要创建一个Thing,否则返回现有的。我想避免使用NPE,所以不要!!。是否有更惯用的方式编写此代码(也许更好地使用?:或使用标准功能之一?

class Thing {
}

private var myThing: Thing? = null

fun getThing(): Thing {
    // if null create, otherwise return exiting
    val tempThing = myThing ?: Thing()
    myThing = tempThing
    return tempThing
}

最佳答案

class Thing { }

private var myThing: Thing? = null

fun getThing() = myThing ?: Thing().also { myThing = it }

10-05 23:34