Byte.parseByte("0") // Java: Gives 0
'0'.toByte() // Kotlin: Gives 48
The Kotlin behavior is to return the char code.
Byte.parseByte("0") // Java: Gives 0
'0'.toByte() // Kotlin: Gives 48
The Kotlin behavior is to return the char code.
â0â.toByte() // Gives 0 as Java
In the first line you parse in the second you cast to byte.
fun main() {
//sampleStart
println("0".toByte())
println('0'.toByte())
//sampleEnd
}
fun main() {
//sampleStart
println('d'.toByte())
println("d".toByte())
//sampleEnd
}
Also 'd'.toByte()
works, while "d".toByte()
fails with a âNumberFormatExceptionâ
The only way I found to do that is
char.toString().toByte()
You could create an extension
fun Char.parseByte() = this.toString().toByte()
fun Char.parseByte() :Byte {
if(this !in '0'..'9') throw NumberFormatException(this.toString())
return (this - '0').toByte()
}