How to convert String to Long in Kotlin?

前端 未结 11 1007
旧时难觅i
旧时难觅i 2021-01-31 13:00

So, due to lack of methods like Long.valueOf(String s) I am stuck.

How to convert String to Long in Kotlin?

相关标签:
11条回答
  • 2021-01-31 13:23

    string.toLong()

    where string is your variable.

    0 讨论(0)
  • 2021-01-31 13:29

    It's interesting. Code like this:

    val num = java.lang.Long.valueOf("2");
    println(num);
    println(num is kotlin.Long);
    

    makes this output:

    2
    true
    

    I guess, Kotlin makes conversion from java.lang.Long and long primitive to kotlin.Long automatically in this case. So, it's solution, but I would be happy to see tool without java.lang package usage.

    0 讨论(0)
  • 2021-01-31 13:31

    String has a corresponding extension method:

    "10".toLong()
    
    0 讨论(0)
  • 2021-01-31 13:31

    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

    0 讨论(0)
  • 2021-01-31 13:36

    If you don't want to handle NumberFormatException while parsing

     var someLongValue=string.toLongOrNull() ?: 0
    
    0 讨论(0)
  • 2021-01-31 13:37

    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
    
    0 讨论(0)
提交回复
热议问题