St.Antario
St.Antario

Reputation: 27435

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?

Upvotes: 0

Views: 38

Answers (1)

jwvh
jwvh

Reputation: 51271

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.

Upvotes: 1

Related Questions