如何在Scala中将Option数组初始化为None

6

我在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()时的行为。
2个回答

10

最简单的方法是:

Array.fill(6)(None:Option[A])

另外,您可以更改类的构造函数,以接受默认参数,例如:

class A(val neighbors: Array[Option[A]] = Array.fill(6)(None))

2
如果Array.fillthis()构造函数中,就不需要在None上进行类型注释,因为neighbors的类型已知,数组的类型可以被推断出来。 - Luigi Plinge

2
也许像这样吗?
def this() = this(Array.fill(6) {Option.empty})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接