How to cast String into Int and Long?

Viewed 7294

In Java we use

Integer.valueOf(str)

and

Long.valueOf(str)

to get the integer but how can we do the same in Kotlin?

5 Answers

You can just use toInt, toLong, and similar conversion extensions.

For example:

val i: Int = str.toInt()
val l: Long = str.toLong()

There's also toIntOrNull, etc. in case your strings might not be valid numbers:

val i: Int? = str.toIntOrNull()

Kotlin has extension methods for String class that do the same but more elegantly.

str.toInt()
str.toLong()

Note that you can write extension methods yourself as well.

Kotlin define extension function in StringNumberConversions.kt like toInt, toLong etc. These functions internally invoke standard java function like java.lang.Integer.parseInt(...) or java.lang.Long.parseLong(...)

You can use them like :

"123".toInt()
"123".toLong()

These are Extension methods available for Strings to parse in KOTLIN:

    str.toBoolean()
    str.toInt()
    str.toLong()
    str.toFloat()
    str.toDouble()
    str.toByte()
    str.toShort()

it is better to

val str = ""
val quotaInteger = str.toDouble().toInt()

cos sometime end give us like "123.22", if we use toInt(), it will throw out NumberFormatException

Related