Are Kotlin data types built off primitive or non-primitive Java data types?

前端 未结 2 1057
清酒与你
清酒与你 2020-12-11 14:17

I am new to Kotlin and was playing around with the data types. I took an Int type and then tried to cast it as a Double by saying num as Doub

2条回答
  •  悲&欢浪女
    2020-12-11 15:08

    This is because Kotlin does not work like Java in widening numbers.

    There are no implicit widening conversions for numbers in Kotlin. for example, you can write something in Java as below:

    int a = 1;
    double b = a;
    

    However, you can't write something in Kotlin. for example:

    val a:Int = 1  
    //             v--- can't be widening
    val b:Double = a
    

    This is because everything in Kotlin is object, there is no primitive types, so you should convert an Int to a Double explicitly, for example:

    val a:Int = 1  
    //               v--- convert it explicitly by `toDouble()` method
    val b:Double = a.toDouble()
    

提交回复
热议问题