https://kotlinlang.org logo
Title
r

Robert

01/28/2019, 7:38 PM
What is the correct way to compare Byte to Int?
if (myByte.compareTo(myInt) == 0)
?
if (myByte.toInt() == myInt)
?
if (myByte == myInt.toByte())
? Something else? Or can I force implicit conversion somehow, as I have a lot of these comparisons?
j

jlleitschuh

01/28/2019, 7:42 PM
if (myByte.toInt() == myInt)
would be the most appropriate I think.
r

Robert

01/28/2019, 7:43 PM
@jlleitschuh Cool. Is there any reasoning to it? Or is it personal preference?
j

jlleitschuh

01/28/2019, 7:45 PM
if (myByte == myInt.toByte())
If there is an overflow in the int to byte conversion, you'll have weird behavior.
if (myByte.compareTo(myInt) == 0)
This is just confusing from a readability perspective and I don't even know if it will compile.
h

hudsonb

01/28/2019, 7:46 PM
I definitely wouldn't narrow the `Int`:
if (myByte == myInt.toByte())
.
123456.toByte()
is
64
.
r

Robert

01/28/2019, 7:49 PM
Okay, thanks, then I'll go with the
myByte.toInt()