gpt4 book ai didi

kotlin - 如何在 Kotlin 中比较 Short 和 Int?

转载 作者:行者123 更新时间:2023-12-02 09:15:44 26 4
gpt4 key购买 nike

我有一个 Short我需要检查其值的变量。但是编译器提示 Operator '==' cannot be applied to 'Short' and 'Int'当我做一个简单的等于检查时:

val myShort: Short = 4
if (myShort == 4) // <-- ERROR
println("all is well")
那么,执行等于检查的最简单、“最干净”的方法是什么?
这是我尝试过的一些事情。
第一个将 4 整数转换为 short(看起来很奇怪,在原始数字上调用函数)
val myShort: Short = 4
if (myShort == 4.toShort())
println("all is well")
下一个将short转换为int(应该没有必要,现在我有两个int,而我真的不需要任何int)
val myShort: Short = 4
if (myShort.toInt() == 4)
println("all is well")

最佳答案

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

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

looks weird, invoking a function on a primitive number



但它实际上并没有调用函数,它们被内化并编译为字节码,以 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

另见: another Q&A concerning numeric conversions .

关于kotlin - 如何在 Kotlin 中比较 Short 和 Int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47289295/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com