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")
Referential equality ('===') The negated counterpart of === in Kotlin is !== which is used to compare if both the values are not equal to each other. For values which are represented as primitive types at runtime (for example, Int), the === equality check is equivalent to the == check.
In Kotlin, we use structural equality (==) to evaluate if both values are the same or equal. This is the same as the equals() method in Java. Therefore, if list1 == list2 is true, both lists have the same size and contain the same elements in exactly the same order.
Using the compareTo() function to compare Kotlin strings While the previous methods return a boolean value ( true or false ), compareTo() returns an integer: Returns 0 if the main string and the other string are equal. Returns a negative number if the other string's ASCII value is bigger than the main string.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With