Kotlin中的Int和Integer有什么区别? [英] What is the difference between Int and Integer in Kotlin?
问题描述
我尝试在Kotlin中使用Int和Integer类型. Kotlin中的Int和Integer类型之间有区别吗?还是相同?
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
是从Number
派生的Kotlin类. 参阅文档
Int
is a Kotlin Class derived from Number
. See doc
[Int]表示一个32位有符号整数.在JVM上,的非空值 这种类型表示为原始类型int的值.
[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
是Java类.
如果要在Kotlin规范中搜索整数",则没有Kotlin Integer
类型.
If you were to search the Kotlin spec for "Integer", there is no Kotlin Integer
type.
如果在IntelliJ中使用表达式is Integer
,则IDE警告...
If you use the expression is Integer
in IntelliJ, the IDE warns...
在Kotlin中不应使用这种类型,而应使用Int.
This type shouldn't be used in Kotlin, use Int instead.
Integer
与Kotlin Int可以很好地互操作,但是它们的行为确实存在细微的差异,例如:
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
在Java中,有时需要显式装箱"整数作为对象.在Kotlin中,仅将可空整数(Int?
)装箱.显式尝试将非空整数装箱将产生编译器错误:
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?)
但是Int
和Integer
(java.lang.Integer
)在大多数情况下都将被相同对待.
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"
这篇关于Kotlin中的Int和Integer有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!