0

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?

Timmy
  • 4,098
  • 2
  • 14
  • 34
St.Antario
  • 26,175
  • 41
  • 130
  • 318

1 Answers1

1

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.

jwvh
  • 50,871
  • 7
  • 38
  • 64
  • You mean this is faster? – St.Antario Aug 01 '17 at 07:43
  • Perhaps, but I think you'd be hard pressed to find a measurable difference in performance. This is just slightly more concise and offers a bit more readability and clarity-of-purpose, IMHO. – jwvh Aug 01 '17 at 07:50