Kotlin Convert String to Int

In the tutorial, JavaSampleApproach will show you how to convert Kotlin String to Int.

Related posts:
Kotlin Convert String to Long


Working environment:
– Java 8
– Kotlin 1.1.61

Kotlin toInt() method

String.toInt(): Int

– use method signature: public inline fun String.toInt(): Int

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

String.toInt(radix: Int): Int

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

Exception:

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

    Kotlin toIntOrNull() method

    String.toIntOrNull(): Int?

    Method signature: public fun String.toIntOrNull(): Int?
    -> Parses the string to an Int 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.

    String.toIntOrNull(radix: Int): Int?

    Method signature: public fun String.toIntOrNull(radix: Int): Int?
    -> Parses the string to an Int 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.

    Last updated on April 9, 2018.



    Related Posts


    Got Something To Say:

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

    *