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?
答案 0 :(得分:2)
你可以这样做:
class InitTest {
var v: Int = _
def int(v : Int) = {
this.v = v
}
}
由于v
具有值类型,因此无法为其分配null
。但是,Scala允许您使用_
来表示“归零”值。对于数字,这是零,对于指针为null。表示未初始化值的好方法。