Kotlin Convert String to Long

In the tutorial, JavaSampleApproach will guide you how to convert Kotlin String to Long.

Related posts:
Kotlin Convert String to Int


Working environment:
– Java 8
– Kotlin 1.1.61

I. Kotlin toLong() method

1 String.toLong(): Long

– use method signature: public inline fun String.toLong(): Long

Strig.toLong() will throw a NumberFormatException if the string is not a valid representation of a number.
String.toLong() just uses Integer.parseLong of Java for converting
-> detail: public inline fun String.toLong(): Long = java.lang.Long.parseLong(this)

2 String.toLong(radix: Int): Long

If we want to work with radix, we can use another method signature toLong(radix: Int)
-> detail: public inline fun String.toLong(radix: Int): Long = java.lang.Long.parseLong(this, checkRadix(radix))

Exception:

  • String.toLong(radix: Int) will throw a NumberFormatException if the string is not a valid representation of a number.
  • String.toLong(radix: Int) will throw a IllegalArgumentException if the radix is not a valid radix.
  • String.toLong(radix: Int) just uses Long.parseLong(this, checkRadix(radix)) of Java for converting,
    -> detail: public inline fun String.toLong(radix: Int): Long = java.lang.Long.parseLong(this, checkRadix(radix))

    II. Kotlin toLongOrNull() method

    1. String.toLongOrNull(): Long?

    Method signature: public fun String.toLongOrNull(): Long?
    -> Parses the string to an Long number and returns a number or null in case the string is not a valid representation of a number.
    It does not throw any exception.

    2. String.toLongOrNull(radix: Int): Long?

    Method signature: public fun String.toLongOrNull(radix: Int): Long?
    -> Parses the string to an Long number and returns null in-case the string is not a valid representation of a number.
    And IllegalArgumentException will be thrown when radix is not a valid radix for string to number conversion.



    By grokonez | December 14, 2017.


    Related Posts


    Got Something To Say:

    Your email address will not be published. Required fields are marked *

    *