stella stella - 3 months ago 13
Scala Question

How to initialize a field by calling a method

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?

Answer

You can do this:

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

Since v has a value type, there is no way of assigning null to it. However, Scala lets you use _ to represent the "zeroed" value. For numbers, that is zero and for pointers that is null. Good way of representing uninitialized values.

Comments