如何在Kotlin中比较Short和Int?

gro*_*190 2 kotlin

我有一个Short变量,我需要检查的值.但编译器抱怨说Operator '==' cannot be applied to 'Short' and 'Int'当我做一个简单的等于检查时:

val myShort: Short = 4
if (myShort == 4) // <-- ERROR
    println("all is well")
Run Code Online (Sandbox Code Playgroud)

那么最简单,"最干净"的方法是什么等于检查?

以下是我尝试过的一些事情(说实话,我都不喜欢).

第一个将4整数转换为short(看起来很奇怪,在原始数字上调用一个函数)

val myShort: Short = 4
if (myShort == 4.toShort())
    println("all is well")
Run Code Online (Sandbox Code Playgroud)

下一个将短路转换为int(不应该是必要的,现在我有两个整数,当我不需要任何时候)

val myShort: Short = 4
if (myShort.toInt() == 4)
    println("all is well")
Run Code Online (Sandbox Code Playgroud)

hot*_*key 5

基本上,将它与一个小常数进行比较的"最干净"的方法是myShort == 4.toShort().

但是如果你想比较一个Short更宽类型的变量,myShort改为转换以避免溢出:myShort.toInt() == someInt.

看起来很奇怪,在原始数字上调用一个函数

但它实际上并没有调用函数,它们是内部化的并且编译为字节码,以对JVM自然的方式操作数字,例如,字节码为myShort == 4.toShort():

ILOAD 2      // loads myShort
ICONST_4     // pushes int constant 4
I2S          // converts the int to short 4
IF_ICMPNE L3 // compares the two shorts
Run Code Online (Sandbox Code Playgroud)

另请参阅:有关数字转换的其他问答.

  • @ gromit190,`4 as Short`将不起作用,请参阅我参考的问答解释:/sf/ask/3179456451/原始的Java数据类型 (2认同)