Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching on case classes with * (varargs) parameter

I have two case class like:

case class B(value:Int)
case class A(a:String, b:B*) extends ALike

and I want to do pattern match on an instance of A:

def foo(al:ALike) = {
  al match {
    case A(a, bs) => ...
  }
}

Scalac doesn't understand that bs is a Seq[B] and thinks that it is just one B. Why is that the case and how should I do pattern match on it?

like image 365
Omid Avatar asked Jun 16 '26 23:06

Omid


1 Answers

It's a varargs argument, so you need to explain that to the compiler explicitly. Use the following case expression:

def foo(al:ALike) = {
  al match {
    case A(a, bs @ _*) => ...
  }
}
like image 99
Zoltán Avatar answered Jun 20 '26 01:06

Zoltán