一旦分配了一个非null值,将a从var更改为val的属性?
如果Kotlin会添加一个属性,一旦赋值为非空值,那么var属性将被更改为val,这意味着您不能再更改该值了吗?
val? context Context? = null ... ... ... context = this ... ... ... context = this.applicationContext //would be an error since context //is val
以上只是一个例子,它是多么有用…
我认为这可能是你真正想要在这种情况下:
val context:Context by lazy { this }
具有“特殊”行为的各种属性都使用委托属性进行处理。
所有的功能请求应该通过正式的Kotlin问题跟踪器 。 其实,已经有你的建议KT-7180的要求。
这是一个可能的实现(从问题):
class InitOnceVar<T>() : ReadWriteProperty<Any?, T> { private var initialized = false private var value: T? = null override fun get(thisRef: Any?, desc: PropertyMetadata): T { if (!initialized) throw IllegalStateException("Property ${desc.name} should be initialized before get") return value } override fun set(thisRef: Any?, desc: PropertyMetadata, value: T) { if (initialized) throw IllegalStateException("Property ${desc.name} could be initialized only once") this.value = value initialized = false } }
这里是你如何使用它:
var x: String by InitOnceVar() x = "star" x = "stop" //Exception
这是可能的:
fun test() { val s : String println(s) // Error: Variable 's' must be initialized s = "Hello" println(s) s = "World!" // Error: Val cannot be reassigned }
否则,没有办法做到这一点。 例如,如果您希望将其作为成员属性,那么编译器就不可能知道方法是否曾经被调用,以及是否允许分配。
@ ligi的答案是一个不错的选择。
- 项目不会与Kotlin 1.1.3一起构建
- Kotlin智能转换不适用于LinearLayout.LayoutParams
- Kotlin – MainActivity扩展AppCompatActivity,onRequestPermissionsResult函数未找到,不能被覆盖
- 未解决的参考:使用greendao和kotlin的DaoSession
- Travis CI:Maven未能获得Kotlin 1.1.1对Linux的依赖
- 在Kotlin for Android中使用Pair时的性能
- 如何使用OnClickListener创建简单的事件//更改文本或颜色
- Kotlin添加自定义监听器在Android上点击小部件
- 从1.0.2 – 1.0.3升级Kotlin:java.lang.NoSuchMethodError:没有虚方法provideInjectedData $ app_compileDebugKotlin()