Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Int vs Integer: type mismatch, found: Int, required: String

Tags:

scala

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.

like image 906
pcjuzer Avatar asked Oct 14 '09 13:10

pcjuzer


2 Answers

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

like image 100
Flaviu Cipcigan Avatar answered Sep 23 '22 08:09

Flaviu Cipcigan


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
like image 27
Eastsun Avatar answered Sep 25 '22 08:09

Eastsun