14

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.

3 Answers 3

19

This question is almost a duplicate of: Scala can't multiply java Doubles? - 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

Sign up to request clarification or add additional context in comments.

Comments

2
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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.