I'm currently trying out kotlin, and I have a simple example here:
var byteToAdd: Byte = 3
var byteArray = byteArrayOf(1, 2, 3, 4, 5)
byteArray[0] += byteToAdd
println(byteArray[0])
But when executing, I get an error on line 3 because it says, that byteToAdd
is an Integer
, even though I set the type of byteToAdd
to Byte
on line 1.
Why is this happening?
This line with the +=
operator is equivalent to this longer call - you can actually convert between the two with intention actions in IntelliJ, if you invoke it on the operator:
byteArray[0] = byteArray[0].plus(byteToAdd)
The issue here is that the plus
operator you're calling on Byte
is returning an Int
(I'm assuming because there's no guarantee the result will fit in a Byte
), which can't be implicitly converted back to Byte
to be put back in the array.
You can fix this by using this longer syntax, and doing an additional conversion of the result back to Byte
:
byteArray[0] = byteArray[0].plus(byteToAdd).toByte()
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