我在Scala(2.9.1)中定义了一个类,如下所示:
class A(val neighbors: Array[Option[A]]) {
def this() = this(new Array[Option[A]](6))
// class code here ...
}
我的问题是,当我想要将邻居初始化为
None
时,它被初始化为null。我尝试了这个方法,但编译器报错说“not found: type None”:class A(val neighbors: Array[Option[A]]) {
def this() = this(new Array[None](6))
// class code here ...
}
我可以这样做,实现所需的行为,但似乎并不太优雅:
class A(val neighbors: Array[Option[A]]) {
def this() = this(Array(None, None, None, None, None, None))
// class code here ...
}
所以,我的问题是,最好的方法是什么?
编辑:我指的是调用
new A()
时的行为。
Array.fill
在this()
构造函数中,就不需要在None
上进行类型注释,因为neighbors
的类型已知,数组的类型可以被推断出来。 - Luigi Plinge