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

但在大多数情况下,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"

Kotlin相关问答推荐

我可以检测一个函数是否在Kotlin中被递归调用(即,重入)吗?

升级使用jOOQ Gradle插件生成代码失败

Kotlin-elvis算子don';不使用map.get()

使函数同时挂起和取消挂起

如何注入返回通用列表的转换器?

为什么 Kotlin 在将协变类型参数转换为不变类型参数时会产生 Unchecked Cast 警告?

使用 kotlin 流删除 map 中具有某些相似性的值

如何在 Kotlin 中不受约束?

为什么没有remember 的 mutableStateOf 有时会起作用?

Moshi:解析单个对象或对象列表(kotlin)

如何使用 Hilt 注入应用程序:ViewModel 中的上下文?

Kotlin:内部类如何访问在外部类中声明为参数的变量?

如何使用 gradle 脚本 Kotlin 构建文件构建可运行的 ShadowJar?

Jetpack Compose – LazyColumn 不重组

在调用Kotlin数据类中的超类构造函数之前访问函数

如何将 CameraView 与 Jetpack Compose 一起使用?

我应该使用Kotlin数据类作为JPA实体吗?

在 Kotlin 中编写一个等于 Int.MIN_VALUE 的十六进制整数文字

Android Jetpack Compose 中的文本渐变

将协程更新到 1.2.0 后构建失败:META-INF/atomicfu.kotlin_module