scalacollectionsscala-option

Scala ifNotPresent concise form


I have the following collection:

private val commandChain: mutable.Buffer[mutable.Buffer[Long]] = ArrayBuffer()

I need to do the following:

def :->(command: Long) = {
  commandChain.headOption match {
    case Some(node) => node += command
    case None => commandChain += ArrayBuffer(command)
  }
}

Is there more concise form of this than pattern matching?


Solution

  • You could just go with a simple if...else statement. No pattern matching and no Option unwrapping.

    def :->(command: Long): Unit = 
      if (commandChain.isEmpty) commandChain += ArrayBuffer(command)
      else                      commandChain.head += command
    

    BTW, this is way more mutable data structures and side effects than is seen in most idiomatic (i.e. "good") Scala.