tags:

views:

672

answers:

3

I type these to the scala interpreter:

val a : Integer = 1;
val b : Integer = a + 1;

And I get the message:

<console>:5: error: type mismatch;
 found   : Int(1)
 required: String
       val b : Integer = a +1
                            ^

Why? How can I solve this? This time I need Integers due to Java interoperability reasons.

A: 

First of all you should use java.lang.Integer instead of Integer.

Currently I don't know why the error occurs.

a is an instance of java.lang.Integer and this type doesn't have a method named +. Furthermore there is no implicit conversion to Int.

To solve this you can try this:

scala> val a: java.lang.Integer = 1
a: java.lang.Integer = 1

scala> val b: java.lang.Integer = a.intValue + 1
b: java.lang.Integer = 2
michael.kebe
+3  A: 
Welcome to Scala version 2.7.3.final (Java HotSpot(TM) Client VM, Java 1.6.0_16).
Type in expressions to have them evaluated.
Type :help for more information.

scala> implicit def javaIntToScala(n: java.lang.Integer) = n.intValue

javaIntToScala: (java.lang.Integer)Int

scala> val a: java.lang.Integer = 1

a: java.lang.Integer = 1

scala> val b: java.lang.Integer = a + 1

b: java.lang.Integer = 2
Eastsun
+5  A: 

This question is almost a duplicate of this - you can look at my answer as well, as the idea is similar.

As Eastsun already hinted, the answer is an implicit conversion from an java.lang.Integer (basically a boxed int primitive) to a scala.Int, which is the Scala way of representing JVM primitive integers.

implicit def javaToScalaInt(d: java.lang.Integer) = d.intValue

And interoperability has been achieved - the code snipped you've given should compile just fine! And code that uses scala.Int where java.lang.Integer is needed seems to work just fine due to autoboxing. So the following works:

def foo(d: java.lang.Integer) = println(d)
val z: scala.Int = 1
foo(z)

Also, as michaelkebe said, do not use the Integer type - which is actually shorthand for scala.Predef.Integer as it is deprecated and most probably is going to be removed in Scala 2.8.

EDIT: Oops... forgot to answer the why. The error you get is probably that the scala.Predef.Integer tried to mimic Java's syntactic sugar where a + "my String" means string concatenation, a is an int. Therefore the + method in the scala.Predef.Integer type only does string concatenation (expecting a String type) and no natural integer addition.

-- Flaviu Cipcigan

Flaviu Cipcigan