Question

How to Convert String to Long in Kotlin

kotlinstring-parsing

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
  • JSON fields
  • command-line arguments
  • form inputs
  • CSV or log files

Your program must convert those strings into numeric types before doing calculations, storing IDs, or validating ranges. Kotlin gives you both a strict option (toLong()) and a safe option (toLongOrNull()).

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 null instead of crashing."

That makes it much easier to handle uncertain input safely.

Take Quiz

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

Because "abc" is not a valid Long, toLongOrNull() returns null.

Example: handling invalid input

fun main() {
    val input = "abc"

    val result = input.toLongOrNull()

    if (result != null) {
        println("Valid long: $result")
    } else {
        println("Invalid number")
    }
}

This is the beginner-friendly pattern you will use often in Kotlin.

Example: trimming spaces first

fun main() {
    val input = " 12345 "
    val result = input.trim().toLongOrNull()

    println(result)
}

If your input may contain extra spaces, call trim() before converting.

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

  1. input is assigned the string "2048".
  2. input.toLongOrNull() tries to parse the text as a Long.
  3. Because "2048" is a valid whole number, the result is 2048L.
  4. number now holds a non-null Long value.
  5. The condition number != null is true.
  6. Kotlin runs println(number + 1).
  7. The output is 2049.

Now look at invalid input:

fun main() {
    val input = "two thousand"
    val number = input.toLongOrNull()

    if (number != null) {
        println(number + 1)
    } else {
        println("Invalid input")
    }
}

What changes?

  1. input contains "two thousand".
  2. toLongOrNull() tries to parse it.
  3. The text is not a valid Long.
  4. The result is null.
  5. number != null is false.
  6. Kotlin runs the else block.
  7. The output is Invalid input.

This shows why toLongOrNull() is useful for unpredictable 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()
Take Quiz

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

val numbers = listOf("1", "2", "x", "4")
    .mapNotNull { it.toLongOrNull() }

This converts only valid numeric strings and skips invalid ones.

This style is common in data processing code.

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() returns Long?, not Long.

Better:

val number: Long? = "123".toLongOrNull()

Or provide a default:

val number: Long = "123".toLongOrNull() ?: 0L

3. Expecting decimal strings to work

Broken example:

val number = "12.5".toLongOrNull()

Why it fails:

  • Long is an integer type.
  • Decimal text should be parsed as Double or Float instead.

4. Ignoring whitespace

Potential issue:

val number = " 42 ".toLongOrNull()

Depending on the source of input, extra spaces can cause trouble. A safe habit is:

val number = " 42 ".trim().toLongOrNull()

5. Confusing Int and Long

val small = "123".toInt()
val large = "123".toLong()

Use Long when values may be larger than Int can hold.

6. Forgetting the L suffix in literals

val fallback = 0L

Using 0L makes the literal a Long. This avoids type mismatch issues when working with Long values.

Comparisons

ApproachReturnsOn invalid inputBest use case
toLong()LongThrows NumberFormatExceptionWhen input is trusted and must be valid
toLongOrNull()Long?Returns nullWhen input may be invalid
toInt()IntThrows NumberFormatExceptionSmaller integer values
toDouble()DoubleThrows NumberFormatExceptionDecimal numbers
toDoubleOrNull()Double?Returns nullSafe decimal parsing

toLong() vs toLongOrNull()

val a = "100".toLong()        // 100
val b = "100".toLongOrNull()  // 100
val c = "abc".toLongOrNull()  // null

Use toLong() when invalid input should be treated as a real program error. Use toLongOrNull() when invalid input is expected and should be handled safely.

Java style vs Kotlin style

In Java, you may see:

Long.valueOf("123")

In Kotlin, the idiomatic style is:

"123".toLong()

Kotlin prefers readable extension functions on the value itself.

Take Quiz

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() returns null if parsing fails.
  • Long is for whole numbers, not decimals.
  • toLongOrNull() returns Long?, so handle nullability.
  • Use L suffix for Long literals, for example 10L.

Common valid inputs

"0".toLong()
"42".toLong()
"-99".toLong()

Common invalid inputs

"abc".toLongOrNull()   // null
"12.5".toLongOrNull()  // null
"".toLongOrNull()      // null

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.

Why does toLongOrNull() return Long??

Because parsing may fail. Kotlin uses null to represent that failure safely.

How do I provide a fallback value if parsing fails?

Use the Elvis operator:

val value = input.toLongOrNull() ?: 0L
Take Quiz

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

  1. Create a list of strings containing both valid and invalid number values.
  2. Convert each string to Long safely.
  3. Ignore values that cannot be converted.
  4. Print the final list of valid Long values.
  5. Print the sum of the valid values.
Take Quiz

Keep learning

Related questions

View more