Kotlin numeric literals

I noticed that I can convert a double value to an integer like this.

var array = kotlin.arrayOfNulls<Int>(10)

for( i in array.indices ){
    array[i] = ( Math.random().toInt() )
}

If it Math.random()returns a double value, how does a double value have a method called toInt ()? Are numeric values ​​objects?

+4
source share
3 answers

Yes, instances of numeric types are Kotlin objects. Quote from Kotlin Docs :

In Kotlin, everything is an object in the sense that we can call member functions and properties for any variable. Some types are built-in, because their implementation is optimized, but to the user they look like ordinary classes.

(, Double Double?) JVM.

+4

Java , Number, intValue. , API .

+1

Kotlin . , NULL , . (Docs)

(.toInt(), .toLong() ..) , , , -. , , , "" .

Math.random().toInt()  // Kotlin

(int) Math.random();   // Generated bytecode decompiled to Java

, , ( , Int?), valueOf :

val n: Int? = 25

Integer n = Integer.valueOf(25);

, :

array[i] = Math.random().toInt()

array[i] = Integer.valueOf((int) Math.random());

:

IntArray ( , int[] Java) Array<Int> ( , Integer[] Java). , lambda.

var array = IntArray(10) { Math.random().toInt() }

Java-:

int[] array = new int[10];
for (int i = 0; i < 10; i++) {
    array[i] = (int) Math.random();
}
+1

Source: https://habr.com/ru/post/1680574/


All Articles