一旦分配了一个非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 } 

具有“特殊”行为的各种属性都使用委托属性进行处理。

所有的function请求应该通过正式的Kotlin问题跟踪器 。 其实,已经有你的建议KT-7180的要求。

这是一个可能的实现(从问题):

 class InitOnceVar() : ReadWriteProperty { 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的答案是一个不错的选择。