Avatar ·

How to convert a string to Long type in Kotlin? Safe ways and error handling

Hello everyone! I just started learning Kotlin after Java, and I have a problem with converting a string to a Long number. I need to read a numeric value from a text field in an application and perform arithmetic operations on it.

\n\n

Here is an example of my code:

\n\n
val input = "1234567890123"\nval number: Long = input.toLong()\nprintln(number * 2)
\n\n

This works when the string is guaranteed to contain a valid number. But what if the user enters something like "abc123" or "12.34"? Then the program crashes with NumberFormatException. In Java, I used try-catch or checked via Long.parseLong, but are there any more elegant built-in methods in Kotlin?

\n\n

Another question: how to handle the case when the string can be null? For example, wh