Kotlin Convert String to Int

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

Related posts:
Kotlin Convert String to Long


Working environment:
– Java 8
– Kotlin 1.1.61

I. Kotlin toInt() method

1 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)

2 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))

    II. Kotlin toIntOrNull() method

    1. 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.

    2. 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 JavaSampleApproach | December 14, 2017.


    Related Posts


    Got Something To Say:

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

    *