Why doesn't Kotlin perform automatic type-casting?

后端 未结 3 748
醉酒成梦
醉酒成梦 2021-01-12 04:21
var a : Double
a = Math.sin(10) // error: the integer literal does not conform to the expected type Double
a = Math.sin(10.0) //This compiles successfully
println(a)         


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-01-12 05:28

    Kotlin does not allow implicit conversions of numeric types. There is a misconception that implicit conversions are "no harm, no foul" ... which is wrong.

    The process in Java for implicit conversions is more complicated than you think, read the docs to see what all is entailed. And then you can try to analyze all of the cases that can go wrong.

    Kotlin, does not want the compiler to guess as to your intention, so it makes everything in the language explicit, including numeric type conversions. As explained in the Kotlin docs for Explicit Conversions it says clearly:

    Due to different representations, smaller types are not subtypes of bigger ones. [...] As a consequence, smaller types are NOT implicitly converted to bigger types. [...] We can use explicit conversions to widen numbers.

    And the documentation shows one such sample of where things can go wrong, but there are many others.

    Nor can you just cast one numeric type to another, as mentioned here in incorrect comments and answers. That will only result in a nice runtime error. Instead look at the numeric conversion functions such as toInt() and toDouble() found on the numeric types, such as on the Number class.

    Explicitness is part of the Kotlin personality, and it is not planned to change.

提交回复
热议问题