El Hippo
El Hippo

Reputation: 389

Collections in Scala class

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

Answers (1)

0__
0__

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:

  • you are using a 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 collection
  • you should avoid null in Scala. There are better abstractions for signalising optional values, in particular Option.
  • perhaps you can also find a sensible other value in place of null here, for example the empty collection.
  • overriding methods and constructors is usually considered bad style. Note that you can also use default values. Here is a suggestion: case class Plopp(name: String, multiline: Set[String] = Set.empty) (implying collection.immutable.Set).

Upvotes: 2

Related Questions