How to Convert String to Long in Kotlin Without Losing Your Mind: Breakdown of Typical Mistakes
\n\nEvery Kotlin developer sooner or later faces the task: you need to take a string entered by a user, received from an API response, or read from a file, and turn it into a number of type Long. It seems simple, right? But right here, out of the blue, beginners (and even experienced programmers) make mistakes that lead to app crashes, blank screens, and sleepless debugging nights.
In this article, we will break down the five most common mistakes when converting String to Long in Kotlin. You will learn not only how to fix them but also how to write code that won't break at the first invalid input. Let's go!
Mistake #1: Naive use of toLong() without exception handling
\n\nThe most straightforward way is to call the toLong() method on a string. Yes, it works, but only if the string contains a valid number. Otherwise — hello, NumberFormatException!
val userInput = "123abc"\nval number: Long = userInput.toLong() // Throws NumberFormatException!\n\nWhy is this bad? A runtime exception is always a risk. If your application doesn't handle it, the user will see a crash.
\n\nHow to fix? Use try-catch or, even better, a safe alternative — toLongOrNull().
val userInput = "123abc"\nval number: Long? = userInput.toLongOrNull() // Returns null, no exception\nprintln(number) // null\n\nThe toLongOrNull() method is your savior. If the string cannot be converted, it simply returns null, and you can handle that case calmly.
Mistake #2: Ignoring null and empty strings
\n\nIn Kotlin, types are explicitly divided into nullable and non-null. If you try to call toLong() on a string that could be null, the compiler won't let you. But there's a catch: an empty string ("") is not null, and it will also throw an exception.
val nullableString: String? = null\n// nullableString.toLong() // Compilation error: only safe (?.) or non-null asserted (!!.) calls allowed\n\nval emptyString = ""\nemptyString.toLongOrNull() // null, all good\n\nPractical tip: Always check the string for emptiness or use toLongOrNull() together with the Elvis operator ?:.
fun parseUserAge(input: String?): Long {\n return input?.toLongOrNull() ?: 0L // If null or not a number — return 0\n}\n\nThis approach makes the code idiomatic and safe.
\n\nMistake #3: Forgetting about spaces and invisible characters
\n\nUsers are unpredictable creatures. They might accidentally put a space before or after the number. A string from a file might contain newline characters \\n. The toLongOrNull() method doesn't trim the string — it expects the string to consist only of digits (and possibly a minus sign).
val dirtyString = " 42 "\ndirtyString.toLongOrNull() // null, because there are spaces\n\nSolution: Always call trim() before conversion.
val cleanString = dirtyString.trim()\nval number: Long? = cleanString.toLongOrNull()\nprintln(number) // 42\n\nThis is one of the simplest and most effective ways to avoid bugs. Remember the rule: trim before you convert.
\n\nMistake #4: Problems with localization and separators
\n\nNumbers are written differently in different countries. In the US and Russia, commas (1,234) or spaces (1 234) are used for thousands separators, and a dot separates decimals. In Europe, it's the opposite: a comma is the decimal separator. Kotlin by default expects a "clean