在 Scala 中,“println(1,2)”是如何工作的?
在 Scala (2.7.7final) 中,Predef.println
方法被定义为具有以下签名:
def println (x : Any) : Unit
怎么会这样,那么以下内容有效:
scala> println(1,2)
(1,2)
编译器是否自动将逗号分隔的参数列表转换为一个元组?用什么魔法?这里是否存在隐式转换,如果是,是哪一个?
In Scala (2.7.7final), the Predef.println
method is defined as having the following signature:
def println (x : Any) : Unit
How come, then that the following works:
scala> println(1,2)
(1,2)
Does the compiler automatically convert a comma-separated list of arguments into a Tuple? By what magic? Is there an implicit conversion going on here, and if so, which one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,如果没有适当的多参数方法和一个适当的单参数方法,编译器将尝试将逗号分隔的参数转换为元组。这不是隐式转换,只是编译器黑客。这是一个有些争议的功能,并且未来可能会发生变化,因为工作计划围绕统一元组和参数列表的处理进行。
Yes, the compiler will attempt to convert comma separated arguments into tuples, if there are no appropriate multi-argument methods and a single appropriate one-argument method. It's not an implicit conversion, just a compiler hack. This is a somewhat controversial feature, and will probably undergo changes going forward, as work is planned around unifying the treatment of tuples and argument lists.