Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String to Long in Kotlin?

Tags:

kotlin

People also ask

What is the correct syntax to convert string to a long in Kotlin?

string.toLong() Parses the string as a [Long] number and returns the result.

What is the correct syntax to convert the string 42 to a long in Kotlin?

toLongOrNull() to convert the string to a Long , return a null if the string is not a valid representation of a Long.

How do you change a string value in Kotlin?

Strings are immutable in Kotlin. That means their values cannot be changed once created. To replace the character in a string, you will need to create a new string with the replaced character.


1. string.toLong()

Parses the string as a [Long] number and returns the result.

@throws NumberFormatException if the string is not a valid representation of a number.

2. string.toLongOrNull()

Parses the string as a [Long] number and returns the result or null if the string is not a valid representation of a number.

3. str.toLong(10)

Parses the string as a [Long] number and returns the result.

@throws NumberFormatException if the string is not a valid representation of a number.

@throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.

public inline fun String.toLong(radix: Int): Long = java.lang.Long.parseLong(this, checkRadix(radix))

4. string.toLongOrNull(10)

Parses the string as a [Long] number and returns the result or null if the string is not a valid representation of a number.

@throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.

public fun String.toLongOrNull(radix: Int): Long? {...}

5. java.lang.Long.valueOf(string)

public static Long valueOf(String s) throws NumberFormatException

String has a corresponding extension method:

"10".toLong()

Extension methods are available for Strings to parse them into other primitive types. Examples below:

  • "true".toBoolean()
  • "10.0".toFloat()
  • "10.0".toDouble()
  • "10".toByte()
  • "10".toShort()
  • "10".toInt()
  • "10".toLong()

Note: Answers mentioning jet.String are outdated. Here is current Kotlin (1.0):

Any String in Kotlin already has an extension function you can call toLong(). Nothing special is needed, just use it.

All extension functions for String are documented. You can find others for standard lib in the api reference


Actually, 90% of the time you also need to check the 'long' is valid, so you need:

"10".toLongOrNull()

There is an 'orNull' equivalent for each 'toLong' of the basic types, and these allow for managing invalid cases with keeping with the Kotlin? idiom.