简体   繁体   English

为什么作业不是陈述

[英]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.

相关问题 为什么这些日志语句不打印? - Why are these log statements not printing? Kotlin:相互指派 - Kotlin: Mutual assignments 为什么无法访问的语句方法不会导致编译错误? - Why do unreachable statements method not result in a compilation error? Kotlin/Android 中的“赋值不是表达式”错误 - "Assignments are not expressions" error in Kotlin/Android 分配不是表达式,并且在此上下文中仅允许表达式 - Assignments are not expressions, and only expressions are allowed in this context 将Java转换为Kotlin后出现“赋值不是表达式错误” - “Assignments are not expressions error” after converting Java to Kotlin 分配不是表达式,在这种情况下只能使用表达式-Kotlin - Assignments are not expressions and only expressions are allowed in this context - Kotlin 赋值不是表达式,在这种情况下只允许使用表达式 - Kotlin - Assignments are not expressions, and only expressions are allowed in this context - Kotlin 为什么非详尽的 when 表达式会导致编译器错误,而 when 语句却不会? - Why do non-exhaustive when expressions cause compiler error, but when statements don't? if 语句:赋值不是表达式,在这个上下文中只允许表达式 kotlin - If statement: Assignments are not expressions, and only expressions are allowed in this context kotlin
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM