How to initialize a field by calling a method

时间:2016-08-23 15:36:45

标签: scala class

The following class refuses to compile:

class InitTest { // Class 'InitTest' must either be declared abstract
                 // or implement abstract member 'v: Int'

  var v: Int

  def int(v : Int) = {
    this.v = v 
  }
}

I was kind of surprise by that we can't just leave values "uninitialized". In Java, it would be assigned with null. In Scala, it does not compile. How to do this in Scala?

1 个答案:

答案 0 :(得分:2)

你可以这样做:

class InitTest {
  var v: Int = _
  def int(v : Int) = {
    this.v = v 
  }
}

由于v具有值类型,因此无法为其分配null。但是,Scala允许您使用_来表示“归零”值。对于数字,这是零,对于指针为null。表示未初始化值的好方法。