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?
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?
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
将与Kotlin Int很好地互操作,但它们在行为上确实有一些细微的差异,例如:
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
在Java中,有时需要将整数显式地"装箱"为对象.在Kotlin中,只有可为空的整数(Int?
)被装箱.显式try 框选不可为空的整数将导致编译器错误:
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?)
但在大多数情况下,Int
和Integer
(java.lang.Integer
)将受到同等对待.
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"