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
最佳答案
这似乎是 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]
。然后使用 toString
方法转换 WrappedArray
,这就是 "hello %s%n"中的
。我认为这就是发生的事情。%s
使用的方法
在第二个版本中,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
,您就可以跨越打字阶段。
关于scala - Predef.readLine 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7693872/