简体   繁体   中英

Scala can't recognize which method to call

I want to run a bit of Java in Scala console. 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?

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()

I was using 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 .

Convert it to java.lang.Integer and it will work.

See also boxing and unboxing in Scala .

I recommend to use the new String interpolators available in Scala 2.10.X. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM