Imagine I have a Kotlin program with a variable b
of type Byte
, into which an external system writes values greater than 127
. "External" means that I cannot change the type of the value it returns.
val a:Int = 128
val b:Byte = a.toByte()
Both a.toByte()
and b.toInt()
return -128
.
Imagine I want to get the correct value (128
) from the variable b
. How can I do it?
In other words: What implementation of magicallyExtractRightValue
would make the following test run?
@Test
fun testByteConversion() {
val a:Int = 128
val b:Byte = a.toByte()
System.out.println(a.toByte())
System.out.println(b.toInt())
val c:Int = magicallyExtractRightValue(b)
Assertions.assertThat(c).isEqualTo(128)
}
private fun magicallyExtractRightValue(b: Byte): Int {
throw UnsupportedOperationException("not implemented")
}
Update 1: This solution suggested by Thilo seems to work.
private fun magicallyExtractRightValue(o: Byte): Int = when {
(o.toInt() < 0) -> 255 + o.toInt() + 1
else -> o.toInt()
}