Why doesn't Kotlin perform automatic type-casting?

后端 未结 3 767
醉酒成梦
醉酒成梦 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:16

    Automatic type casting for numeric types can lead to losing precision. Just consider following java code:

    double hoursSinceUnixEra = System.currentTimeMillis()/1000/60/60;
    

    The intention was not to cut the result to full hours, although it compiles without any warning in Java.

    val hoursSinceUnixEra = System.currentTimeMillis()/1000/60/60;
    someObject.doubleValue = hoursSinceUnixEra
    

    Above Kotlin code won't compile due to unexplicit casting.

    Issue of this type can be very hard to find and fix and it's the reason behind this decision. You can still explicitly convert type:

    val value = 3
    Math.sin(value.toDouble())
    

提交回复
热议问题