Reputation: 107
I noticed that I can convert a double value into an integer like this.
var array = kotlin.arrayOfNulls<Int>(10)
for( i in array.indices ){
array[i] = ( Math.random().toInt() )
}
If Math.random()
returns a double value, how can a double value have a method named toInt()? Are numerical values also objects?
Upvotes: 6
Views: 3020
Reputation: 89668
The Kotlin compiler aims to use primitives as much as possible. This means using primitives unless a variable is nullable or has to be boxed because generics are involved. (Docs)
In the case of these conversion functions (.toInt()
, .toLong()
, etc.), the variables that these functions are called on will be primitives, and simple casts will be used on them in the bytecode. So there's no boxing happening here, these are still primitives, but you can call "functions" on them as syntactic sugar.
Math.random().toInt() // Kotlin
(int) Math.random(); // Generated bytecode decompiled to Java
In case an otherwise primitive value is assigned to a nullable variable, such as in your case (assigned to an array element which is of type Int?
), it will be boxed using a valueOf
call at the assignment:
val n: Int? = 25
Integer n = Integer.valueOf(25);
So your specific assignment will be a combination of the two above examples, and will translate like this:
array[i] = Math.random().toInt()
array[i] = Integer.valueOf((int) Math.random());
In case you're interested in a simpler replacement for your example code:
You can use an IntArray
(primitive array, int[]
in Java) instead of an Array<Int>
(array of boxed values, Integer[]
in Java). You can also initialize it in the constructor's second parameter using a lambda.
var array = IntArray(10) { Math.random().toInt() }
This is roughly equivalent to this Java code:
int[] array = new int[10];
for (int i = 0; i < 10; i++) {
array[i] = (int) Math.random();
}
Upvotes: 1
Reputation: 272772
Yes, instances of numeric types are Kotlin objects. Quoting from the Kotlin docs:
In Kotlin, everything is an object in the sense that we can call member functions and properties on any variable. Some types are built-in, because their implementation is optimized, but to the user they look like ordinary classes.
In practice, non-nullable instances (e.g. Double
as opposed to Double?
) are represented under the hood with JVM primitives.
Upvotes: 5
Reputation: 106508
In Java, any object that extends Number
has the ability to invoke intValue
. I would presume that Kotlin is exposing that API there.
Upvotes: 1