Int和Integer在Kotlin上有什么区别?

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

Int是一个从Number派生的Kotlin类。 请参阅文档

[Int]表示一个32位有符号整数。 在JVM上,这种类型的非空值被表示为基本类型int的值。

Integer是一个Java类。

如果您要在Kotlin规范中搜索“Integer”,则不存在Kotlin Integer类型。

如果在IntelliJ中使用is Integer表达式,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 

在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?) 

但是IntIntegerjava.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" 

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

在Java平台上,除非我们需要一个可为空的数字引用(例如Int?)或涉及泛型,否则数字在物理上存储为JVM基本类型。 在后者的情况下,数字是盒装的。

这意味着, Int表示为基本int 。 只有在涉及可空性或泛型的情况下,必须使用后备包装类型Integer 。 如果从头开始使用Integer ,则始终使用包装类型,而不使用原始的int

一个Int是一个原始类型。 这相当于JVM int。

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