Convert String to Long in Kotlin with example

This tutorial covers various methods for converting strings to/from long values in Kotlin.

A string is a group of characters enclosed in double or single quotes. A long is a numeric value that can represent a whole number.

Kotlin does not automatically convert these types, so you have to write code manually to convert from one type to another.

Convert String to Long value

  • use valueOf method The valueOf() method allows converting a string to different types such as integer and long.
import java.lang.Long;

fun main() {
 val value = Long.valueOf("11");
 println(value); //11
 println(value is kotlin.Long);// true
}
  • use toLong method

The toLong or toLongOrNull methods takes a string object and returns a long value. The toLongOrNull method returns either null or a long value.

The toLong() method throws a java.lang.NumberFormatException for invalid input.

fun main() {
 val str ="11a";
 val numb: Long = str.toLong()
 println(numb)

 println(numb is kotlin.Long);

}

Exception in thread “main” java.lang.NumberFormatException: For input string: “11a” at java.lang.NumberFormatException.forInputString (:-1) at java.lang.Long.parseLong (:-1) at java.lang.Long.parseLong (:-1)

fun main() {
    val str = "11"
    val numb = str.toLongOrNull()
    println(numb)  // 11
    println(numb is kotlin.Long)  // true
}

Convert String to Long type in Kotlin

  • use toString method Every object has a toString() method. A Long value can be converted to a String using the toString method.
fun main() {
    val number: Long = 1156L;
    val str: String = number.toString();
    println(str); //1111
    println(str is kotlin.String);// true
}
  • use String template interpolation Syntax String templates provide expressions inside a string literal.

Syntax is "${expression}"

expression is a simple variable of expression using arthematic operatos.

fun main() {
    val number: Long = 123;
    val str: String = "$number"
    println(str); //123
    println(str is kotlin.String);// true
}
  • use String.format() function The format() function in the String class is used to create formatted strings. It formats the string to include different values at runtime using options.

For example, the following code accepts an input long and converts it to a string using the %d option.

fun main() {
    val number: Long = 123;
    val str: String = String.format("%d", number)
    println(str); //123
    println(str is kotlin.String);// true
}

Conclusion

Learned multiple ways to convert String to Long and Long to String in Kotlin.