This article explores different ways to convert a string to a long in Kotlin.

1. Using toLong() function

The standard solution to convert a string to a long with the toLong() function. It throws a NumberFormatException if the string does not contain a valid long.

Download Code

Output:

The Long value is 100000000

 
Note that there are several other extension methods available in Kotlin to parse strings into other primitive types. These are toInt(), toBoolean(), toFloat(), toDouble(), toByte() and toShort().

2. Using toLongOrNull() function

Alternatively, you can use the toLongOrNull() function, which parses the string as a Long and returns the result or null if the string is not a valid representation of a number.

Download Code

Output:

The Long value is 100000000

 
This can be shortened with the safe call operator and a scope function.

Download Code

Output:

The Long value is 100000000

3. Using java.lang.Long.valueOf() function

Finally, you can use Java’s Long.valueOf() function from the java.lang package that returns the long value specified by the string.

That’s all about converting a string to a Long in Kotlin.