【发布时间】: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 类型的语句?
【问题讨论】:
-
这是为了避免错误而做出的决定。
-
您也可以使用
get和set语法,这样更易读。 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