为什么分配不是陈述 [英] why assignments are not statements

查看:59
本文介绍了为什么分配不是陈述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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.但是我认为这不太可读.

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.

那么为什么我不能在Kotlin中将赋值用作表达式主体?为什么赋值不只是类型为Unit的语句?

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

这篇关于为什么分配不是陈述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆