Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Numeric Literals

Tags:

kotlin

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?

like image 389
gktg1414 Avatar asked Jul 01 '17 23:07

gktg1414


People also ask

What are literals in Kotlin?

Kotlin constants are fixed values that does not change during program execution. These fixed values are called literals. Kotlin Constants can be of any basic data types. For example, Integer constants, Floating point constants, Character constants, String literals etc.

Is Num a Kotlin data type?

(a) Kotlin Number Data TypesKotlin number data types are used to define variables which hold numeric values and they are divided into two groups: (a) Integer types store whole numbers, positive or negative (b) Floating point types represent numbers with a fractional part, containing one or more decimals.

How many numerical data types are there in Kotlin?

Numbers. Number types are divided into two groups: Integer types store whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types are Byte , Short , Int and Long .

What does ?: Mean in Kotlin?

AndroidMobile DevelopmentApps/ApplicationsKotlin. In Kotlin, "!!" is an operator that is known as the double-bang operator. This operator is also known as "not-null assertion operator". This operator is used to convert any value to a non-NULL type value and it throws an exception if the corresponding value is NULL.


Video Answer


2 Answers

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.

like image 175
Oliver Charlesworth Avatar answered Oct 13 '22 10:10

Oliver Charlesworth


In Java, any object that extends Number has the ability to invoke intValue. I would presume that Kotlin is exposing that API there.

like image 43
Makoto Avatar answered Oct 13 '22 09:10

Makoto