繁体   English   中英

为什么作业不是陈述

[英]why assignments are not statements

我有以下代码:

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
}

我知道我可以写:

class Presenter {
    var view : View? = null
}

然后在代码中只调用presenter.view = View()presenter.view = null而不是attachView / detachView 但我认为这不太可读。

那么为什么我不能在Kotlin中使用赋值作为表达式主体呢? 为什么赋值只是一个Unit类型的声明?

无论我们喜欢与否,这只是语言创作者所做出的设计决策。 有关详细信息,请参阅此讨论:

https://discuss.kotlinlang.org/t/assignment-not-allow-in-while-expression/339

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM