Kotlin可为空的变量赋值

在Kotlin中,这个代码是否有更简短的语法:

if(swipeView == null){ swipeView = view.find<MeasureTypePieChart>(R.id.swipeableView) } 

首先我试过这个:

  swipeView ?: view.find<MeasureTypePieChart>(R.id.swipeableView) 

但后来我意识到这不是一个任务,所以代码什么都不做。 然后我试着:

 swipeView = swipeView ?: view.find<MeasureTypePieChart>(R.id.swipeableView) 

哪个工作,但有点冗长。 我会期待这样的事情:

 swipeView ?= view.find<MeasureTypePieChart> 

但不幸的是,这是行不通的。 有没有什么办法用一个简短的语法来完成这个?

我知道我可以这样做:

 variable?.let { it = something } which works. 

更短的语法将避免swipeView永远为null

局部变量

如果swipeView是一个局部变量,那么你可以在初始化时声明它非空:

 val swipeView = ... ?: view.find<MeasureTypePieChart>(R.id.swipeableView) 

函数参数

如果swipeView是一个函数参数,那么你可以使用默认的参数,以确保它永远不会为null

 fun something(swipeView: View = view.find<MeasureTypePieChart>(R.id.swipeableView)) 

类属性

只读

如果swipeView是一个只读的类属性(即val ),那么你可以使用Kotlin内置的Lazy

 val swipeView by lazy { view.find<MeasureTypePieChart>(R.id.swipeableView) } 

易变的

如果swipeView是一个可变的类属性(即var ),那么你可以定义你自己的委托类似Lazy但可变。 例如下面是基于kotlin / Lazy.kt :

 interface MutableLazy<T> : Lazy<T> { override var value: T } fun <T> mutableLazy(initializer: () -> T): MutableLazy<T> = SynchronizedMutableLazyImpl(initializer) fun <T> mutableLazy(lock: Any?, initializer: () -> T): MutableLazy<T> = SynchronizedMutableLazyImpl(initializer, lock) operator fun <T> MutableLazy<T>.getValue(thisRef: Any?, property: KProperty<*>): T = value operator fun <T> MutableLazy<T>.setValue(thisRef: Any?, property: KProperty<*>, value: T) { this.value = value } private object UNINITIALIZED_VALUE private class SynchronizedMutableLazyImpl<T>(initializer: () -> T, lock: Any? = null) : MutableLazy<T>, Serializable { private var initializer: (() -> T)? = initializer @Volatile private var _value: Any? = UNINITIALIZED_VALUE // final field is required to enable safe publication of constructed instance private val lock = lock ?: this override var value: T get() { val _v1 = _value if (_v1 !== UNINITIALIZED_VALUE) { @Suppress("UNCHECKED_CAST") return _v1 as T } return synchronized(lock) { val _v2 = _value if (_v2 !== UNINITIALIZED_VALUE) { @Suppress("UNCHECKED_CAST") (_v2 as T) } else { val typedValue = initializer!!() _value = typedValue initializer = null typedValue } } } set(value) { val _v1 = _value if (_v1 !== UNINITIALIZED_VALUE) { _value = value } else synchronized(lock) { _value = value initializer = null } } override fun isInitialized(): Boolean = _value !== UNINITIALIZED_VALUE override fun toString(): String = if (isInitialized()) value.toString() else "MutableLazy value not initialized yet." } 

用法:

 var swipeView by mutableLazy { view.find<MeasureTypePieChart>(R.id.swipeableView) } 

如果swipeView被读取并且尚未初始化(来自之前的读取或写入),则initializer将仅被调用。

Interesting Posts