4
我已经定义了在斯卡拉(2.9.1)一类,如下所示:如何初始化选项阵列为无斯卡拉
class A(val neighbors: Array[Option[A]]) {
def this() = this(new Array[Option[A]](6))
// class code here ...
}
我的问题是邻居与空值,当我想它初始化初始化为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'的类型已经是已知的,并且可以推断出数组的类型。 –
谢谢,我喜欢在构造函数中使用默认参数。 – astay13