Skip to content

Failure to autobox Int's to Integer's: String.format("%02x", 255) #8661

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
scabug opened this issue Jun 12, 2014 · 2 comments
Closed

Failure to autobox Int's to Integer's: String.format("%02x", 255) #8661

scabug opened this issue Jun 12, 2014 · 2 comments

Comments

@scabug
Copy link

scabug commented Jun 12, 2014

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?

@scabug
Copy link
Author

scabug commented Jun 12, 2014

Imported From: https://issues.scala-lang.org/browse/SI-8661?orig=1
Reporter: Andrew Pennebaker (mcandre)
Affected Versions: 2.11.1

@scabug
Copy link
Author

scabug commented Jun 12, 2014

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants