📜  kotlin Number to Long - Kotlin (1)

📅  最后修改于: 2023-12-03 15:02:32.235000             🧑  作者: Mango

Kotlin Number to Long

In Kotlin, we can convert a Number type to a Long using the toLong() method. The Number type is a generic number type that can hold any type of number in Kotlin, such as Int, Long, Float, Double, etc.

To convert a Number to a Long, we simply call the toLong() method on the Number instance:

val number: Number = 42
val longValue: Long = number.toLong()

Here, we have a Number instance with a value of 42. We then call the toLong() method on this instance to convert it to a Long value.

If the Number instance has a value that cannot be represented as a Long, such as a decimal value, then a kotlin.TypeCastException will be thrown at runtime.

For example:

val decimalValue: Number = 3.14
val longValue: Long = decimalValue.toLong() // Throws TypeCastException

In this case, the Number instance has a decimal value of 3.14, which cannot be represented as a Long. When we try to convert it to a Long, a kotlin.TypeCastException is thrown.

In summary, converting a Number to a Long in Kotlin is as simple as calling the toLong() method on the Number instance. However, we need to be careful to ensure that the Number value can be represented as a Long before doing so.