String to Long in Kotlin: 5 Fatal Mistakes and How to Avoid Them

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

How to Convert String to Long in Kotlin Without Losing Your Mind: Breakdown of Typical Mistakes

\n\n

Every 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.

\n\n

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!

\n\n

Mistake #1: Naive use of toLong() without exception handling

\n\n

The 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!

\n\n
val userInput = "123abc"\nval number: Long = userInput.toLong() // Throws NumberFormatException!
\n\n

Why is this bad? A runtime exception is always a risk. If your application doesn't handle it, the user will see a crash.

\n\n

How to fix? Use try-catch or, even better, a safe alternative — toLongOrNull().

\n\n
val userInput = "123abc"\nval number: Long? = userInput.toLongOrNull() // Returns null, no exception\nprintln(number) // null
\n\n

The toLongOrNull() method is your savior. If the string cannot be converted, it simply returns null, and you can handle that case calmly.

\n\n

Mistake #2: Ignoring null and empty strings

\n\n

In 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.

\n\n
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\n

Practical tip: Always check the string for emptiness or use toLongOrNull() together with the Elvis operator ?:.

\n\n
fun parseUserAge(input: String?): Long {\n    return input?.toLongOrNull() ?: 0L // If null or not a number — return 0\n}
\n\n

This approach makes the code idiomatic and safe.

\n\n

Mistake #3: Forgetting about spaces and invisible characters

\n\n

Users 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).

\n\n
val dirtyString = "  42  "\ndirtyString.toLongOrNull() // null, because there are spaces
\n\n

Solution: Always call trim() before conversion.

\n\n
val cleanString = dirtyString.trim()\nval number: Long? = cleanString.toLongOrNull()\nprintln(number) // 42
\n\n

This is one of the simplest and most effective ways to avoid bugs. Remember the rule: trim before you convert.

\n\n

Mistake #4: Problems with localization and separators

\n\n

Numbers 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

Blogs

Book Recommendations