scala> val input = readLine("hello %s%n", "world")
hello WrappedArray(world)
input: String = ""
scala> val input = Console.readLine("hello %s%n", "world")
hello world
input: String = ""
造成这种差异的原因是什么? (我也尝试编译它,所以它不是REPL的东西。)
Scala版本2.9.0-1
答案 0 :(得分:5)
这似乎是Predef
中的错误:
def readLine(text: String, args: Any*) = Console.readLine(text, args)
当我认为它应该是:
def readLine(text: String, args: Any*) = Console.readLine(text, args: _*)
您使用的第一个版本是Prefef.readLine
。由于缺少_*
类型归属,因此使用args
作为args
的重复参数Console.readLine
的单个第一个参数调用该函数。
在 uncurry 编译阶段,此单个参数将包含在WrappedArray
中,以便将其视为Seq[Any]
。然后使用WrappedArray
方法转换toString
,这是%s
中"hello %s%n"
使用的方法。我认为这就是发生的事情。
在第二个版本中,args
从一开始就被视为Seq[Any]
,并且不会发生任何转化。
整个事情有点搞笑,因为通常编译器不允许你这样做:
scala> def f(s: Int*) = s foreach println
f: (s: Int*)Unit
scala> def g(s: Int*) = f(s)
<console>:8: error: type mismatch;
found : Int*
required: Int
def g(s: Int*) = f(s)
使用Any
,您将超越typer阶段。