Predef.readLine行为

时间:2011-10-07 23:52:07

标签: scala console

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

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阶段。