What is the difference between Int and Integer in Scala?

I was working with a variable that I declared as Integer, and found that> is not a member of Integer. Here is a simple example:

scala> i warning: there were deprecation warnings; re-run with -deprecation for details res28: Integer = 3 scala> i > 3 <console>:6: error: value > is not a member of Integer i > 3 ^ 

Compare this to Int:

 scala> j res30: Int = 3 scala> j > 3 res31: Boolean = false 

What are the differences between Integer and Int? I see a warning about obsolescence, but I don’t understand why it was deprecated and, given that it was, why it doesn’t have a method>.

+45
types scala integer int
Aug 12 '09 at 22:54
source share
5 answers

"What are the differences between Integer and Int?"

An integer is just an alias for java.lang.Integer. Int is a Scala integer with additional capabilities.

Looking in Predef.scala, you can see this alias:

  /** @deprecated use <code>java.lang.Integer</code> instead */ @deprecated type Integer = java.lang.Integer 

However, there is an implicit conversion from Int to java.lang.Integer if you need it, which means you can use Int in methods that accept Integer.

As to why it is deprecated, I can only assume that this was to avoid confusion regarding the type of whole you were working with.

+40
Aug 13 '09 at 13:34
source share

An integer is imported from java.lang.Integer and is only for compatibility with Java. Since this is a Java class, of course, it cannot have a method called "<". EDIT: You can reduce this problem by declaring an implicit conversion from Integer to Int.

  implicit def toInt(in:Integer) = in.intValue() 

You will still receive a rejection warning.

+4
Aug 12 '09 at 23:28
source share

I think the problem you see should be boxing / unpacking of value types and using the Java Integer class.

I think the answer is here: Boxing and unboxing in Scala . Scala does not have implict unlock. You have defined i as the Java Integer class, but in i> 3 , 3, int is also processed.

+4
Aug 12 '09 at 23:29
source share

Integer is a Java class, java.lang.Integer . It differs from the primitive Java int type, which is not a class. It cannot have < because Java does not allow operators to define classes.

Now you may wonder why this type exists at all? Well, primitive types cannot be passed as references, so you cannot pass int method that expects java.lang.Object , equivalent to, for example, Scala AnyRef . To do this, you put this int inside the Integer object, and then pass the Integer .

+1
Aug 13 '09 at 12:17
source share

An integer is imported from java.lang.Integer and is only for compatibility with Java. Since this is a Java class, of course, it cannot have a method called "<".

EDIT: You can reduce this problem by declaring an implicit conversion from Integer to Int.

+1
Dec 13 '12 at 12:52
source share



All Articles