Is Scala implicit conversions prevents auto boxing?

People following me on twitter know that I am in the phase of learning Scala for the past few days. As a java programmer I am comfortable with most of the aspects of Scala (though more to explore in coming days). Recently I came across a problem that gave me an impression that Scala fails in doing auto boxing. Let us take the below example for our further discussions,

object AutoBoxing extends Application
   val intVariable = 2;
    System.out.printf("%d",2); //this line fails during implicit conversion

The above code suffers during implicit conversion from Int to Object with an error

AutoBoxing.scala:4: error: type mismatch;
found : Int
required: java.lang.Object
Note that implicit conversions are not applicable because they are ambiguous:
both method int2Integer in object Predef of type (Int)java.lang.Integer
and method intWrapper in object Predef of type (Int)scala.runtime.RichInt
are possible conversion functions from Int to java.lang.Object
one error found

On skimming through the API documentation of Scala , I came to know of the following object hierarchy

  • Int subclass of AnyVal
  • AnyVal subclass of Any
  • AnyRef subclass of Any
  • Object subclass of AnyRef

As a java programmer we all are aware that System.out.printf accepts object as its second parameter

  public PrintStream printf(String format, Object ... args) {

By now you should have sensed the issue, yes Scala fails when it tries to convert Int to Object (which is of type AnyRef, not in the hierarchy). However the error is not explicit to reason that out. There are few ways to resolve the issue

  • Solution 1 : Using console.printf(…)
  • Solution 2 : Converting explicitly to java.lang.Integer using asInstanceOf
              System.out.printf("%d",intVariable : java.lang.Integer);
  • Solution 3 : Converting to java.lang.Integer using int2Integer

Do you know more way to do this? Eager to learn from you, let me know it !!

Similar problem could occur for any other type of AnyVal. Being said all these; I could find certain enhancement request on Scala with regard to this

Disclaimer: I am a beginner in Scala, pardon my ignorance 🙂

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Furl


2 Responses

  1. you could do:

    val intVariable: java.lang.Integer = 2

  2. val intVariable: java.lang.Integer = 2System.out.printf(“%d”,intVariable);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: