[英]Scala can't recognize which method to call
I want to run a bit of Java in Scala console. 我想在Scala控制台中运行一些Java。 Here's what I get:
这是我得到的:
scala> String.format("hello %d",3);
<console>:8: error: overloaded method value format with alternatives:
(java.util.Locale,java.lang.String,<repeated...>[java.lang.Object])java.lang.String <and>
(java.lang.String,<repeated...>[java.lang.Object])java.lang.String
cannot be applied to (java.lang.String, Int)
String.format("hello %d",3);
Why Scala can't recognize which method to call, if argument set is different, and the ones I provide are quite unambigous? 为什么Scala无法识别调用哪个方法,如果参数集不同,我提供的方法是非常明确的?
What is strange, the same message appears also when I try to call function with arguments which don't match to any of both argument sets, eg String.format()
奇怪的是,当我尝试使用与两个参数集中的任何一个都不匹配的参数调用函数时,也出现相同的消息,例如
String.format()
I was using scala 2.9.1 我使用的是scala 2.9.1
Your arguments don't match the function prototype. 您的参数与函数原型不匹配。 You're calling the function with second argument
scala.Int
which is not a java.lang.Object
. 你用第二个参数
scala.Int
调用函数,它不是java.lang.Object
。
Convert it to java.lang.Integer
and it will work. 将它转换为
java.lang.Integer
,它将工作。
See also boxing and unboxing in Scala . 另请参阅Scala中的装箱和拆箱 。
I recommend to use the new String interpolators available in Scala 2.10.X. 我建议使用Scala 2.10.X中提供的新String插补器。 They are easier to use.
它们更容易使用。
val x = 3
String.format("hello %d", x: Integer)
would be simply: 简单地说:
val x =3
s"hello $x"
尝试
String.format("hello %d",3.asInstanceOf[java.lang.Object]);
另外,你可以让Scala为你做拳击:
String.format("hello %d", 3: Integer)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.