Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the differences between Int and Integer in Scala?

I was working with a variable that I had declared as an Integer and discovered that > is not a member of Integer. Here's 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 that to an Int:

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

What are the differences between Integer and Int? I see the deprecation warning but it's unclear to me why it was deprecated and, given that it has been, why it doesn't have a > method.

like image 433
pr1001 Avatar asked Aug 12 '09 22:08

pr1001


People also ask

What is difference between int and Integer?

A int is a data type that stores 32 bit signed two's compliment integer. On other hand Integer is a wrapper class which wraps a primitive type int into an object. int helps in storing integer value into memory. Integer helps in converting int into object and to convert an object into int as per requirement.

What is the difference between int [] and Integer []?

The major difference between an Integer and an int is that Integer is a wrapper class whereas int is a primitive data type. An int is a data type that stores 32-bit signed two's complement integer whereas an Integer is a class that wraps a primitive type int in an object.

Which is faster int or Integer?

Use int when possible, and use Integer when needed. Since int is a primitive, it will be faster.


2 Answers

"What are the differences between Integer and Int?"

Integer is just an alias for java.lang.Integer. Int is the Scala integer with the extra capabilities.

Looking in Predef.scala you can see this the 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, meaning that you can use Int in methods that take an Integer.

As to why it is deprecated, I can only presume it was to avoid any confusion over which kind of integer you were working with.

like image 121
Richard Dallaway Avatar answered Oct 08 '22 15:10

Richard Dallaway


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

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

You'll still get deprecation warning though.

like image 27
Kim Stebel Avatar answered Oct 08 '22 13:10

Kim Stebel