为什么不能在Scala子类中赋值var? [英] Why can't I assign to var in Scala subclass?

查看:251
本文介绍了为什么不能在Scala子类中赋值var?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下抽象类:

 抽象类A(var is_happy:Boolean){
def toggle_happiness();
}



现在我想定义一个实现 toggle_happiness()方法:

  class B(is_happy:Boolean)extends A(is_happy) {
def toggle_happiness()= {
is_happy =!is_happy
}
}

Scala的编译器给我:

 错误:重新分配给val 
is_happy =!is_happy
^

这里发生了什么?我认为 is_happy 引用我的类中由我的构造函数设置的 var 。是否与名称 is_happy 有冲突?



谢谢,
Dan

解决方案

请参阅这个问题。基本上,Scala认为你试图分配给构造函数参数 is_happy ,而不是 var code> is_happy ,它刚好有相同的名称。一些解决方案是:




  • 创建 var 抽象 (例如 _is_happy )重命名构造函数参数。由于参数名称是您的构造函数/方法的公共API的一部分,因此这可能不可取。



您很幸运在你的情况下在编译时检测到问题。此问题可能会导致在未检测到时非常令人惊讶的运行时行为 。 p>

Suppose I have the following abstract class:

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

And now I want to define a concrete class which implements the toggle_happiness() method:

class B (is_happy : Boolean) extends A (is_happy) {
  def toggle_happiness() = {
    is_happy = !is_happy
  }
}

Scala's compiler gives me:

error: reassignment to val
   is_happy = !is_happy
            ^

What's going on here? I thought that is_happy referred to a var in my class that is set by my constructor. Do I have a conflict with the name is_happy?

Thanks, Dan

解决方案

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.

这篇关于为什么不能在Scala子类中赋值var?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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