Question
I want to convert a String to a Long in Kotlin. In Java, I might use something like Long.valueOf(String), but I cannot find the same style of method in Kotlin.
How can I safely and correctly convert a String to a Long in Kotlin?
Short Answer
By the end of this page, you will understand how Kotlin converts strings into Long values, when to use toLong() versus toLongOrNull(), what happens with invalid input, and how this is typically handled in real Kotlin code.
Concept
Kotlin uses extension functions for many common conversions instead of relying on Java-style static utility methods such as Long.valueOf(...).
For converting a String to a Long, the two most important functions are:
toLong()toLongOrNull()
toLong()
This converts the string directly to a Long.
val id = "123".toLong()
If the string is not a valid number, Kotlin throws an exception:
NumberFormatException
toLongOrNull()
This tries to convert the string, but instead of throwing an exception, it returns null if conversion fails.
val id = "123".toLongOrNull()
This is often the safer choice when input comes from users, files, APIs, or forms.
Why this matters
In real programs, numeric values often arrive as text:
- query parameters from URLs
Mental Model
Think of a String as a label containing text, and a Long as a large-number container.
When you call toLong(), you are asking Kotlin:
"Please read this text and turn it into a whole number."
If the text really looks like a number, the conversion works. If the text contains anything unexpected, the conversion fails.
"42"-> works"9999999999"-> works"hello"-> fails"12.5"-> fails because that is not a whole number
toLongOrNull() is like asking:
"Try to read this as a whole number, and if you can't, just give me
nullinstead of crashing."
That makes it much easier to handle uncertain input safely.
Syntax and Examples
Basic syntax
val number: Long = "123".toLong()
val maybeNumber: Long? = "123".toLongOrNull()
Example: direct conversion
fun main() {
val text = "456"
val value = text.toLong()
println(value)
}
Output:
456
Here, text contains a valid whole number, so toLong() succeeds.
Example: safe conversion
fun main() {
val text = "abc"
val value = text.toLongOrNull()
println(value)
}
Output:
null
Step by Step Execution
Consider this example:
fun main() {
val input = "2048"
val number = input.toLongOrNull()
if (number != null) {
println(number + 1)
} else {
println("Invalid input")
}
}
Step by step
inputis assigned the string"2048".input.toLongOrNull()tries to parse the text as aLong.- Because
"2048"is a valid whole number, the result is2048L. numbernow holds a non-nullLongvalue.- The condition
number != nullis true. - Kotlin runs
println(number + 1). - The output is
2049.
Now look at invalid input:
Real World Use Cases
String-to-Long conversion appears in many real programs.
User input
A user types an ID, age, timestamp, or quantity into a form.
val userId = input.toLongOrNull()
URL and API parameters
A backend service may receive IDs as strings.
val idFromRequest = params["id"]?.toLongOrNull()
Reading CSV or text files
Data files often store numeric values as text.
val columns = line.split(",")
val orderId = columns[0].toLongOrNull()
Database integration
Some systems return values as strings before conversion.
val externalId = rawValue.toLongOrNull()
Command-line tools
Arguments passed to a Kotlin script or app are strings.
val timeout = args.firstOrNull()?.toLongOrNull()
Real Codebase Usage
In real Kotlin codebases, developers usually prefer safe parsing when input is external.
Pattern: validation first
val id = input.toLongOrNull()
if (id == null) {
println("Invalid ID")
return
}
println("Processing ID $id")
This is a common guard clause pattern: reject bad input early.
Pattern: default value
val pageSize = input.toLongOrNull() ?: 10L
If parsing fails, the code uses a fallback value.
Pattern: nullable pipeline
val result = input
.trim()
.toLongOrNull()
This is common when cleaning user input before conversion.
Pattern: fail fast for trusted data
val configValue = envVar.toLong()
If the program expects valid numeric configuration and invalid data should stop execution, toLong() may be appropriate.
Pattern: mapping collections
Common Mistakes
1. Using toLong() on untrusted input
Broken example:
val input = "abc"
val number = input.toLong() // Throws NumberFormatException
Why it fails:
"abc"is not a valid whole number.toLong()throws an exception.
Better:
val number = input.toLongOrNull()
2. Forgetting that toLongOrNull() returns a nullable type
Broken example:
val number: Long = "123".toLongOrNull()
Why it fails:
toLongOrNull()returnsLong?, notLong.
Better:
number: ? = .toLongOrNull()
Comparisons
| Approach | Returns | On invalid input | Best use case |
|---|---|---|---|
toLong() | Long | Throws NumberFormatException | When input is trusted and must be valid |
toLongOrNull() | Long? | Returns null | When input may be invalid |
toInt() | Int | Throws NumberFormatException | Smaller integer values |
toDouble() |
Cheat Sheet
Quick reference
val n1 = "123".toLong() // Long
val n2 = "123".toLongOrNull() // Long?
Safe parsing
val value = input.toLongOrNull()
if (value != null) {
println(value)
}
With default value
val value = input.toLongOrNull() ?: 0L
Trim input first
val value = input.trim().toLongOrNull()
Important rules
toLong()throws if parsing fails.toLongOrNull()returnsnullif parsing fails.Longis for whole numbers, not decimals.toLongOrNull()returnsLong?, so handle nullability.- Use suffix for literals, for example .
FAQ
How do I convert a String to Long in Kotlin?
Use toLong() if the string is definitely valid, or toLongOrNull() if it may be invalid.
What is the Kotlin equivalent of Long.valueOf()?
The idiomatic Kotlin equivalent is "123".toLong() or "123".toLongOrNull().
What happens if the string is not a valid number?
toLong() throws NumberFormatException, while toLongOrNull() returns null.
Should I use toLong() or toLongOrNull()?
Use toLongOrNull() for user input, API data, or files. Use toLong() when the input is trusted and should always be valid.
Can I convert decimal text like "12.5" to Long?
No. Long only stores whole numbers. Use toDouble() or toDoubleOrNull() for decimal values.
Mini Project
Description
Build a small Kotlin program that reads a list of string inputs and converts valid values to Long. This demonstrates safe parsing, null handling, and filtering invalid data, which are common tasks in real applications that process user input or imported text data.
Goal
Create a program that converts a list of numeric strings into Long values and ignores invalid entries safely.
Requirements
- Create a list of strings containing both valid and invalid number values.
- Convert each string to
Longsafely. - Ignore values that cannot be converted.
- Print the final list of valid
Longvalues. - Print the sum of the valid values.
Keep learning
Related questions
Accessing Kotlin Extension Functions from Java
Learn how Kotlin extension functions are compiled and how to call them correctly from Java with clear examples and common pitfalls.
Allow HTTP and HTTPS in Android 9 Pie with Network Security Configuration
Learn how Android 9 Pie handles cleartext HTTP traffic and how to allow HTTP and HTTPS safely using network security config.
Android AlarmManager Example: Scheduling Tasks with AlarmManager
Learn how to use Android AlarmManager to schedule tasks, set alarms, and handle broadcasts with a simple beginner example.