views:

128

answers:

1
+3  Q: 

varargs puzzle?

I'm sure the answer is pretty simple, but I got stuck in this:

Welcome to Scala version 2.7.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_14).
Type in expressions to have them evaluated.
Type :help for more information.

scala> def f(x:Int*)=0
f: (Int*)Int

scala> val xs:Seq[Int]=1::2::3::4::Nil
xs: Seq[Int] = List(1, 2, 3, 4)

scala> f (xs)
<console>:7: error: type mismatch;
 found   : Seq[Int]
 required: Int
       f (xs)
          ^

How I build an 'Int*' ?

+8  A: 

To unpack a sequence into the argument list, use _*

scala> f(xs: _*)
res1: Int = 0
Ben James
yes! that works!... feels a little like "forcing" the type, though
GClaramunt
Well, it is forcing the type. The correct type is an argument list, not an argument which is a list. By the way, it works for any type of sequence, as well as any type that can be converted into a sequence, so you could have passed `List` directly. Also, it is symmetric. You could do `xs match { case List(ys @ _*) => ... }`.
Daniel