Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Int and Integer in Kotlin?

Tags:

I have tried using Int and Integer types in Kotlin.Although I don't see any difference. Is there a difference between Int and Integer types in Kotlin?Or are they the same?

like image 207
idjango Avatar asked Sep 18 '17 08:09

idjango


People also ask

What is the difference between int and integer?

In Java, int is a primitive data type while Integer is a Wrapper class. int, being a primitive data type has got less flexibility. We can only store the binary value of an integer in it. Since Integer is a wrapper class for int data type, it gives us more flexibility in storing, converting and manipulating an int data.

Can I use integer instead of int?

Integer helps in converting int into object and to convert an object into int as per requirement. int provides less flexibility as compare to Integer as it only allows binary value of an integer in it. Integer on other hand is more flexible in storing and manipulating an int data.

How does Kotlin compare int?

== operator in Kotlin only compares the data or variables, whereas in Java or other languages == is generally used to compare the references. The negated counterpart of == in Kotlin is != which is used to compare if both the values are not equal to each other.


Video Answer


1 Answers

Int is a Kotlin Class derived from Number. See doc

[Int] Represents a 32-bit signed integer. On the JVM, non-nullable values of this type are represented as values of the primitive type int.

Integer is a Java Class.

If you were to search the Kotlin spec for "Integer", there is no Kotlin Integer type.

If you use the expression is Integer in IntelliJ, the IDE warns...

This type shouldn't be used in Kotlin, use Int instead.

Integer will interoperate well with Kotlin Int, but they do have some subtle differences in behavior, for example:

val one: Integer = 1 // error: "The integer literal does not conform to the expected type Integer" val two: Integer = Integer(2) // compiles val three: Int = Int(3) // does not compile val four: Int = 4 // compiles 

In Java, there are times where you need to explicitly "box" an integer as an object. In Kotlin only Nullable integers (Int?) are boxed. Explicitly trying to box a non-nullable integer will give a compiler error:

val three: Int = Int(3) // error: "Cannot access '<init>': it is private in 'Int' val four: Any = 4 // implicit boxing compiles (or is it really boxed?) 

But Int and Integer (java.lang.Integer) will be treated the same most of the time.

when(four) {     is Int -> println("is Int")     is Integer -> println("is Integer")     else -> println("is other") } //prints "is Int" when(four) {     is Integer -> println("is Integer")     is Int -> println("is Int")     else -> println("is other") } //prints "is Integer" 
like image 91
Les Avatar answered Sep 29 '22 22:09

Les