DEV Community

loading...

Kotlin Convert String to Int

loizenai profile image loizenai ・1 min read

https://grokonez.com/kotlin/kotlin-convert-string-int

Kotlin Convert String to Int

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

Related posts:

Working environment:

  • Java 8
  • Kotlin 1.1.61

    Kotlin toInt() method

    String.toInt(): Int

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

package com.javasampleapproach.string2int

fun main(args : Array) {
    // use method:
    // -> public inline fun String.toInt(): Int = java.lang.Integer.parseInt(this)
    val number: Int = "123".toInt();
    println(number) // 123
    
    // if the string is not a valid representation of a number
    // -> throw NumberFormatException
    try{
        "12w".toInt();
    }catch(e: NumberFormatException){
        println(e.printStackTrace())
        // -> print on console:
        /*
        java.lang.NumberFormatException: For input string: "12w"
            at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
            at java.lang.Integer.parseInt(Integer.java:580)
            at java.lang.Integer.parseInt(Integer.java:615)
            at com.javasampleapproach.string2int.ConvertString2IntKt.main(ConvertString2Int.kt:12)
        */
    }
}
  • 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)

More at:

https://grokonez.com/kotlin/kotlin-convert-string-int

Kotlin Convert String to Int

Discussion (0)

pic
Editor guide