Why doesn't Kotlin perform automatic type-casting?

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

    We all know that Kotlin has both non-nullable Int and nullable Int?.

    When we use Int? this happens: Kotlin actually 'boxes' JVM primitives when Kotlin needs a nullable reference since it's aimed at eliminating the danger of null references from code.

    Now look at this: (assuming this is a compilable code)

    val a: Int? = 1
    val b: Long? = a
    

    Kotlin doesn't perform implicit type conversion because of this thing happens. If Kotlin did implicit type conversions, b should be 1. but since a is a boxed Int and b is a boxed Long, a == b yields false and falls into contradiction, since its == operator checks for equals() and Long's equals() checks other part to be Long as well.

    Check the documentation:

    • Explicit Conversions in Kotlin
    • https://kotlinlang.org/docs/reference/basic-types.html
    • https://kotlinlang.org/docs/reference/equality.html

提交回复
热议问题