- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Pattern matching with varargs
Thu, 2009-07-30, 16:18
Hello everybody,
Axel
View this message in context: Pattern matching with varargs
Sent from the Scala - User mailing list archive at Nabble.com.
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?
ThanksAxel
View this message in context: Pattern matching with varargs
Sent from the Scala - User mailing list archive at Nabble.com.
Thu, 2009-07-30, 16:47
#2
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. :-)
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