You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In pure Java, an int primitive is autoboxed with Generics into java.lang.Integer when supplied to String.format:
String.format("%02x", 255) => "ff"
Scala supports some implicit conversions, but fails to transform scala.Int to java.lang.Integer here. Attempting to run the same code in Scala results in an error about method/argument mismatch:
scala> String.format("%02x", 255)
:8: error: overloaded method value format with alternatives:
(x$1: java.util.Locale,x$2: String,x$3: Object*)String
(x$1: String,x$2: Object*)String
cannot be applied to (String, Int)
String.format("%02x", 255)
As a workaround, Scala programmers can explicitly convert the Int to an Integer:
scala> String.format("%02x", new Integer(255))
res1: String = ff
But this is a confusing experience for new Scala users coming from Java. The error message isn't particularly helpful, either. In the future, could Scala please automatically convert Int's to Integer's when a method expects an Object?
The text was updated successfully, but these errors were encountered:
@som-snytt said:
String.format takes Objects; no generics involved. This question has a long history on stackoverflow. For this use case, there are more modern alternatives to using String.format directly, such as the f interpolator.
In pure Java, an int primitive is autoboxed with Generics into java.lang.Integer when supplied to String.format:
String.format("%02x", 255) => "ff"
Scala supports some implicit conversions, but fails to transform scala.Int to java.lang.Integer here. Attempting to run the same code in Scala results in an error about method/argument mismatch:
scala> String.format("%02x", 255)
:8: error: overloaded method value format with alternatives:
(x$1: java.util.Locale,x$2: String,x$3: Object*)String
(x$1: String,x$2: Object*)String
cannot be applied to (String, Int)
String.format("%02x", 255)
As a workaround, Scala programmers can explicitly convert the Int to an Integer:
scala> String.format("%02x", new Integer(255))
res1: String = ff
But this is a confusing experience for new Scala users coming from Java. The error message isn't particularly helpful, either. In the future, could Scala please automatically convert Int's to Integer's when a method expects an Object?
The text was updated successfully, but these errors were encountered: