Convert a String to a Long in Kotlin
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun toLong(s: String) { try { val value = s.toLong() println("The Long value is $value") } catch (ex: NumberFormatException) { println("The String is non-numeric") } } fun main() { val str = "100000000" toLong(str) } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun toLong(s: String) { val value = s.toLongOrNull() if (value != null) { println("The Long value is $value") } else { println("The String is non-numeric") } } fun main() { val str = "100000000" toLong(str) } |
Output:
The Long value is 100000000
This can be shortened with the safe call operator and a scope function.
|
1 2 3 4 5 6 7 8 9 10 |
fun toLong(s: String) { s.toLongOrNull()?.let { println("The Long value is $it") } } fun main() { val str = "100000000" toLong(str) } |
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.
|
1 2 3 4 5 6 7 |
fun main() { val str = "100000000" val value = java.lang.Long.valueOf(str) println(value) // 100000000 } |
That’s all about converting a string to a Long in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)