Reputation: 389
how do I init collections in a Scala class like "null"? For example
class Plopp(val name: String, var multiline: mutable.Set[String])
And in that class I want to define an aditional contructor like
def this(name: String) = this(name, null)
Everywhere I look there just examples with simple types like String, Int aso.
Update due to the answer:
class Plopp(val name: String, var multiline: Option[Set[String]] = None)
Upvotes: 0
Views: 41
Reputation: 67330
Scala has inherited null
from Java, so you can write basically what you did in your question:
import scala.collection.mutable
class Plopp(val name: String, var multiline: mutable.Set[String]) {
def this(name: String) = this(name,null)
}
Whether this makes sense is a different question:
var
for a mutable collection. you probably want either a val
here (because you mutate the collection in place), or you change to an immutable collectionnull
in Scala. There are better abstractions for signalising optional values, in particular Option
.null
here, for example the empty collection.case class Plopp(name: String, multiline: Set[String] = Set.empty)
(implying collection.immutable.Set
).Upvotes: 2