varargs难题?

GCl*_*unt 5 scala type-mismatch

我确定答案很简单,但我陷入了困境:

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)
          ^
Run Code Online (Sandbox Code Playgroud)

我如何构建'Int*'?

Ben*_*mes 10

要将序列解压缩到参数列表中,请使用 _*

scala> f(xs: _*)
res1: Int = 0
Run Code Online (Sandbox Code Playgroud)

  • 嗯,这是强迫类型.正确的类型是参数列表,而不是作为列表的参数.顺便说一句,它适用于任何类型的序列,以及任何可以转换为序列的类型,因此您可以直接传递`List`.而且,它是对称的.你可以做`xs match {case List(ys @ _*)=> ...}`. (2认同)