Kotlin中Int和Integer有什么区别?

idj*_*ngo 18 kotlin

我尝试在Kotlin中使用Int和Integer类型.虽然我没有看到任何区别.Kotlin中Int和Integer类型之间有区别吗?或者它们是否相同?

Les*_*Les 23

Int是源于的Kotlin类Number. 见文档

[Int]表示32位有符号整数.在JVM上,此类型的非可空值表示为基本类型int的值.

Integer 是一个Java类.

如果您要搜索Kotlin规范中的"整数",则没有Kotlin Integer类型.

如果您使用is IntegerIntelliJ中的表达式,IDE会发出警告...

此类型不应在Kotlin中使用,而是使用Int.

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
Run Code Online (Sandbox Code Playgroud)

在Java中,有时您需要将整数显式"封装"为对象.在Kotlin中,只有Nullable整数(Int?)被装箱.显式尝试打包一个不可为空的整数会产生编译错误:

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?)
Run Code Online (Sandbox Code Playgroud)

但是IntInteger(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"
Run Code Online (Sandbox Code Playgroud)

  • 当与泛型一起使用时,将使用不可为空的`Int`.例如,`List <Int>`将包含盒装整数. (3认同)

San*_*osh 6

A Int是原始类型.这相当于JVM int.

可以为空的Int Int?是盒装类型.这相当于java.lang.Integer.


gue*_*ter 5

只需看看https://kotlinlang.org/docs/reference/basic-types.html#representation

在 Java 平台上,数字在物理上存储为 JVM 原始类型,除非我们需要一个可为空的数字引用(例如 Int?)或涉及泛型。在后一种情况下,数字被装箱。

这意味着,这Int表示为原始的int。只有在涉及可空性或泛型的情况下,才Integer必须使用支持包装类型。如果你Integer从一开始就使用,你总是使用包装器类型而不是原始类型int