Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type mismatch: inferred type is Int but Byte was expected

Tags:

casting

kotlin

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?

like image 214
Adam Avatar asked Aug 10 '18 16:08

Adam


1 Answers

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()
like image 76
zsmb13 Avatar answered Oct 06 '22 00:10

zsmb13