This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Pattern matching with varargs

2 replies
crypter
Joined: 2009-07-30,
User offline. Last seen 42 years 45 weeks ago.
Hello everybody,

I am trying to match case classes with variable arguments in the constructor.

scala> case class Foo(args : String*)
defined class Foo

scala> val f1 = new Foo("one", "two")
f1: Foo = Foo(Array(one, two))

scala> f1 match {
     | case Foo(args) => println(args)
     | case _ => println("something different")
     | }
something different

Is there a way to match the variable argument list (without knowing its length) and put it into an array?

Thanks
Axel
View this message in context: Pattern matching with varargs
Sent from the Scala - User mailing list archive at Nabble.com.
Colin Bullock
Joined: 2009-01-23,
User offline. Last seen 42 years 45 weeks ago.
Re: Pattern matching with varargs

Is there a way to match the variable argument list (without knowing its length) and put it into an array?

scala> fl match {                         
     | case Foo(args @ _*) => println(args)
     | case _ => println("something different")
     | }
Array(one, two)

scala>

The expression args @ _* binds args to the (possibly empty) remainder of the parameter list. Since none have been matched against in this case, this is the entire list. For example, to match instances with at least one parameter:

case Foo(first, rest @ _*) => // got at least one

- Colin
crypter
Joined: 2009-07-30,
User offline. Last seen 42 years 45 weeks ago.
Re: Pattern matching with varargs

Colin Bullock wrote:
>
>
> The expression args @ _* binds args to the (possibly empty) remainder of
> the
> parameter list. Since none have been matched against in this case, this is
> the entire list. For example, to match instances with at least one
> parameter:
>
> case Foo(first, rest @ _*) => // got at least one
>
> - Colin
>
>
Thank you Colin, that was exactly, what I needed. :-)

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland