简体   繁体   中英

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 . But I think this is much less readable.

So why can't I use assignments as expression bodies in Kotlin? Why isn't assignment just a statement of type 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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