kotlin

Methods to convert a String to Long in Kotlin

In this post, we are going to learn different methods that can be used to convert a String value to a Long value in Kotlin.

// define a string
val strVal: String = "123"

// convert to long using toLong()
val result: Long = strVal.toLong()

// print the result 
println(result)

Output

123

If you want to get the Long value from a String value then you can use one of the methods explained in this post.

Use String.toLong() to convert a String to Long

As described in the main code example, we are using the toLong() function to convert a String to Long. This is a String method that provides the Long value from a Kotlin String.

Syntax

String.toLong()

Code Example

fun main() {
    // define a string
    val strVal: String = "901"
    
    // convert to long using toLong()
    val result: Long = strVal.toLong()
    
    // print the result 
    println(result)
}

Output

901

Convert to Long using toLongOrNull() function

A String can also be converted to a Long value using the toLongorNull() function. The best part of using this function is it will not throw an error if the string value is not valid. It will return null if the string value is not valid and a Long value if the string value is valid.

Syntax

String.toLongOrNull()

Code example using a valid String value

// define a string
val strVal: String = "901"

// convert to long using toLongOrNull()
val result: Long? = strVal.toLongOrNull()

if (result != null) {
    print(result)
} else {
    print("string value is not valid")
}

Output

901

Code example using an invalid string value

// define a string
val strVal: String = "901b"

// convert to long using toLongOrNull()
val result: Long? = strVal.toLongOrNull()

if (result != null) {
    print(result)
} else {
    print("string value is not valid")
}

Output

string value is not valid
Was this helpful?