[英]why assignments are not statements
I have the following code: 我有以下代码:
class Presenter {
private var view : View? = null
fun attachView(view: View) = this.view = view // error: Assignment is not a statement
fun detachView() = view = null // error: Assignment is not a statement
}
I know I just can write: 我知道我可以写:
class Presenter {
var view : View? = null
}
and later in code just call presenter.view = View()
and presenter.view = null
instead of attachView
/ detachView
. 然后在代码中只调用presenter.view = View()
和presenter.view = null
而不是attachView
/ detachView
。 But I think this is much less readable. 但我认为这不太可读。
So why can't I use assignments as expression bodies in Kotlin? 那么为什么我不能在Kotlin中使用赋值作为表达式主体呢? Why isn't assignment just a statement of type Unit
? 为什么赋值只是一个Unit
类型的声明?
Whether we like it or not, this was simply a design decision which the language creators made. 无论我们喜欢与否,这只是语言创作者所做出的设计决策。 See this discussion for more details: 有关详细信息,请参阅此讨论:
https://discuss.kotlinlang.org/t/assignment-not-allow-in-while-expression/339 https://discuss.kotlinlang.org/t/assignment-not-allow-in-while-expression/339
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.