Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare a Short with an Int in Kotlin?

Tags:

kotlin

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")
like image 437
birgersp Avatar asked Nov 14 '17 15:11

birgersp


People also ask

How does Kotlin compare int?

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.

How do you compare two items in Kotlin?

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.

How do you use Kotlin CompareTo?

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.


2 Answers

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.

like image 83
hotkey Avatar answered Sep 20 '22 12:09

hotkey


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")
like image 44
Thomas Martin Avatar answered Sep 22 '22 12:09

Thomas Martin