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

我曾尝试在Kotlin中使用Int和Integertypes。虽然我没有看到任何区别。 Kotlin中Int和Integertypes有区别吗?还是它们是一样的?

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

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

Integer是一个Java类。

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

如果在IntelliJ中使用is Integerexpression式,IDE将警告…

这种types不应该在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 '': 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" 

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

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

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

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

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