Home > Blockchain >  Why direct conversion to Char is deprecated for Double and Long types in Kotlin?
Why direct conversion to Char is deprecated for Double and Long types in Kotlin?

Time:08-11

In Kotlin, starting from version 1.5, direct conversion to Char for Double and Long types has marked as deprecated, and it is recommended to invoker the following toInt().toChar() a chain of functions to convert Double/Long to Char.

What prompted the Kotlin developers to abandon the direct conversion to Char for Double and Long types?

What issues can this approach avoid?

fun main() {
    val l = 100_000_000_000 // random big number
    val d = 1.2543534645645362E15 // random big double

    var chUsedDirectToChar = l.toChar()
    var chUsedToIntToChar = l.toInt().toChar() // the same
    println(chUsedDirectToChar == chUsedToIntToChar) // true

    chUsedDirectToChar = d.toChar()
    chUsedToIntToChar = d.toInt().toChar() // the same
    println(chUsedDirectToChar == chUsedToIntToChar) // true
}

CodePudding user response:

You can find the motivation in this KEEP: https://github.com/Kotlin/KEEP/blob/master/proposals/stdlib/char-int-conversions.md

Reverse conversions like Double.toChar() usually make no sense, and it would be more clear if the intent was expressed explicitly by converting the number to Int first and then getting the character corresponding to that Int code.

It is hard to understand what is the char you want for number such as 16.284619, so now you have to explicitly convert it to Int and then to Char

  • Related