【问题标题】:why assignments are not statements为什么赋值不是语句
【发布时间】:2017-07-28 07:32:27
【问题描述】:

我有以下代码:

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 类型的语句?

【问题讨论】:

  • 这是为了避免错误而做出的决定。
  • 您也可以使用getset 语法,这样更易​​读。 kotlinlang.org/docs/reference/…
  • 我没有找到任何记录为什么assignments are NOT expressions in Kotlin 但如果任何读者不知道您可以使用run 将分配视为表达式。例如fun attachView(view: View) = run { this.view = view } 但在这种情况下,您最好使用块函数fun attachView(view: View) { this.view = view },除非您想避免将块函数包装成多行的代码样式。
  • @llya 不是。 Assignments are NOT expressions in Kotlin 但正如 run { ... } 示例“不返回任何有用的值,它的返回类型是 Unit”(Unit-returning functions)。 Kotlin 中的赋值没有返回类型,因为它们不是表达式,但它们可以用作代码块中的最后一条语句来推断函数返回类型 Unit
  • @nhaarman 您能否提供一个可能导致错误的示例?

标签: kotlin


【解决方案1】:

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

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

【讨论】:

  • 这个答案很大程度上依赖于外部链接的内容。如果该页面离线,您的答案将失去大部分价值。所以请edit它并添加一些可以在那里找到的更多细节。考虑一下,如果答案的价值存在于外部网站的内容中,那么该答案很可能会被删除。谢谢!
猜你喜欢
  • 2021-06-10
  • 2017-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-09
  • 2018-12-06
相关资源
最近更新 更多