假设我有一个Kotlin程序,它有一个类型为Byte
的变量b
,外部系统将大于127
的值写入其中."External"表示我不能更改其返回值的类型.
val a:Int = 128
val b:Byte = a.toByte()
a.toByte()
和b.toInt()
都返回-128
.
假设我想要从变量b
获得正确的值(128
).我该怎么做呢?
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()
}