Different ways to convert string to long in Kotlin

Introduction :

In this post, I will show you different ways to convert one string to long in Kotlin. Kotlin provides different methods that make it easy to achieve.

String.toLong() :

String.toLong() parses the string as Long and returns the result. If it is not valid, then it will return NumberFormatException.

fun main() {
    val givenString = "100124"

    print(givenString.toLong())
}

It will print 100124.

String.toLong(radix: Int) :

It parses the string as Long using the provided radix. It throws NumberFormatException if the string is not valid or IllegalArgumentException if the radix is not valid.

fun main() {
    val givenString = "100124"

    print(givenString.toLong(10))
}

It will print 100124.

String.toLongOrNull() and String.toLongOrNull(radix: Int) :

You can use these methods if you don’t want to handle exceptions. toLongOrNull will parse the string as long and return the result or it will return null if the string is not valid.

toLongOrNull(radix: Int) does the same, but it will throw IllegalArgumentException if the radix is not valid.

fun main() {
    var givenString = "100124"


    println(givenString.toLongOrNull())
    givenString = null.toString()

    println(givenString.toLongOrNull())
}

It will print :

100124
null

Similar tutorials :