Zoltán
Zoltán

Reputation: 22176

Can I use pattern matching both by class and variable?

Consider the following example:

def combine(trees: List[CodeTree]): List[CodeTree] =
  if (trees.isEmpty || singleton(trees)) trees
  else trees match {
    case Leaf(cl, wl) :: Leaf(cr, wr) :: tail =>
      Fork(new Leaf(cl, wl), new Leaf(cr, wr), List(cl, cr), wl + wr) :: tail
  }

I would like to know whether I could capture the two Leaf instances into a variable. I would expect a syntax like the following:

def combine(trees: List[CodeTree]): List[CodeTree] =
  if (trees.isEmpty || singleton(trees)) trees
  else trees match {
    case l: Leaf(cl, wl) :: r: Leaf(cr, wr) :: tail =>
      Fork(l, r, List(cl, cr), wl + wr) :: tail
  }

This does not actually compile, but I was hoping for something similar.

Thanks in advance!

Upvotes: 1

Views: 115

Answers (1)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297265

You use colon for types, so you'd have to write something like this:

case (l: Leaf[???]) :: (r: Leaf[???]) :: tail =>

But there's a way to match a pattern and extract it at the same time, which is using the "at" sign:

case (l @ Leaf(cl, wl)) :: (r @ Leaf(cr, wr)) :: tail =>

PS: I have no idea where parenthesis are necessary, so I added them anyway.

Upvotes: 4

Related Questions