Convert String to Long in Kotlin with example

This tutorial explains about multiple ways to convert String to Long and Long to String

There are multiple ways we can convert String to Long type in kotlin.

Convert String to Long value

  • use valueOf method
import java.lang.Long;

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

toLong or toLongOrNull method takes string object and returns an long value. toLongOrNull method returns null or long value.

toLong() method throws java.lang.NumberFormatException: For input string:

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

 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
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.