0

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?

stella
  • 2,546
  • 2
  • 18
  • 33

1 Answers1

2

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.

Alec
  • 31,829
  • 7
  • 67
  • 114