Reputation: 4966
I have a Short
variable that I need to check the value of. But the compiler complains that Operator '==' cannot be applied to 'Short' and 'Int'
when I do a simple equals check:
val myShort: Short = 4
if (myShort == 4) // <-- ERROR
println("all is well")
So what's the simplest, "cleanest" way to do this equals check?
Here are some things I tried.
The first one casts the 4 integer to a short (looks weird, invoking a function on a primitive number)
val myShort: Short = 4
if (myShort == 4.toShort())
println("all is well")
The next one casts the short to an int (shouldn't be necessary, now I have two ints when I shouldn't really need any)
val myShort: Short = 4
if (myShort.toInt() == 4)
println("all is well")
Upvotes: 8
Views: 8847
Reputation: 768
You could also create an infix function instead of ==
. I called it eq
infix fun Short.eq(i: Int): Boolean = this == i.toShort()
And you can use it like this
val myShort: Short = 4
if (myShort eq 4)
println("all is well")
Upvotes: 3
Reputation: 148189
Basically, the 'cleanest' way to compare it with a small constant is myShort == 4.toShort()
.
But if you want to compare a Short
with a wider-type variable, convert myShort
instead to avoid the overflow: myShort.toInt() == someInt
.
looks weird, invoking a function on a primitive number
But it does not actually call the functions, they are intrinsified and compiled to bytecode that operates the numbers in a way that is natural for JVM, for example, the bytecode for myShort == 4.toShort()
is:
ILOAD 2 // loads myShort
ICONST_4 // pushes int constant 4
I2S // converts the int to short 4
IF_ICMPNE L3 // compares the two shorts
See also: another Q&A concerning numeric conversions.
Upvotes: 12