Why can't I assign to var in Scala subclass?

后端 未结 2 901
独厮守ぢ
独厮守ぢ 2021-02-07 10:37

Suppose I have the following abstract class:

abstract class A (var is_happy : Boolean) {
  def toggle_happiness();
}

And now I want to define a

2条回答
  •  旧时难觅i
    2021-02-07 11:32

    See this question. Essentially, Scala thinks that you're trying to assign to the constructor parameter, is_happy, rather than the var, is_happy, which just happens to have the same name. Some solutions are to:

    • Make the var abstract in the base class.
    • Rename the constructor parameter (e.g. _is_happy). Since parameter names are part of the public API of your constructors/methods, this may not be advisable.

    You're fortunate that the problem was detected at compile time in your case. This issue can lead to very surprising runtime behavior when it goes undetected.

提交回复
热议问题