如何比较Kotlin中的Short和Int?

我有一个Shortvariables,我需要检查的值。 但编译器抱怨说,当我做一个简单的equals检查时, Operator '==' cannot be applied to 'Short' and 'Int'

 val myShort: Short = 4 if (myShort == 4) // <-- ERROR println("all is well") 

那么最简单的“最干净的”方法是什么?

这里有一些我尝试过的东西(没有我喜欢,说实话)。

第一个投4个整数到一个短(看起来很奇怪,调用一个原始数字函数)

 val myShort: Short = 4 if (myShort == 4.toShort()) println("all is well") 

下一个将short转换为int(不应该是必须的,现在我有两个int,当我不需要的时候)

 val myShort: Short = 4 if (myShort.toInt() == 4) println("all is well") 

基本上,把它与一个小的常量比较的“最干净”的方法是myShort == 4.toShort()

但是如果你想比较一个Short和一个更宽泛的variables,转换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 

另请参阅: 有关数字转换的另一个问答 。