Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an Option array to None in Scala

I have defined a class in Scala (2.9.1) as follows:

class A(val neighbors: Array[Option[A]]) {
   def this() = this(new Array[Option[A]](6))

   // class code here ...
}

My problem is that neighbors is initialized with nulls, when I would like it to be initialized with None. I tried this, but the compiler complains with the error message "not found: type None":

class A(val neighbors: Array[Option[A]]) {
   def this() = this(new Array[None](6))

   // class code here ...
}

I can do this, which gives the desired behavior, but it doesn't seem very elegant:

class A(val neighbors: Array[Option[A]]) {
   def this() = this(Array(None, None, None, None, None, None))

   // class code here ...
}

So, my question is, what is the best way to do this?

EDIT: I am referring to the behavior when new A() is called.

like image 830
astay13 Avatar asked Nov 27 '11 23:11

astay13


1 Answers

The easiest way to do this would be

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

Additionally you can change your class's constructor to take a default parameter like this:

class A(val neighbors: Array[Option[A]] = Array.fill(6)(None))
like image 173
Moritz Avatar answered Oct 02 '22 15:10

Moritz