How to convert String to Int in Kotlin?

Kotlin

Kotlin Problem Overview


I am working on a console application in Kotlin where I accept multiple arguments in main() function

fun main(args: Array<String>) {
    // validation & String to Integer conversion
}

I want to check whether the String is a valid integer and convert the same or else I have to throw some exception.

How can I resolve this?

Kotlin Solutions


Solution 1 - Kotlin

You could call toInt() on your String instances:

fun main(args: Array<String>) {
    for (str in args) {
        try {
            val parsedInt = str.toInt()
            println("The parsed int is $parsedInt")
        } catch (nfe: NumberFormatException) {
            // not a valid int
        }
    }
}

Or toIntOrNull() as an alternative:

for (str in args) {
    val parsedInt = str.toIntOrNull()
    if (parsedInt != null) {
        println("The parsed int is $parsedInt")
    } else {
        // not a valid int
    }
}

If you don't care about the invalid values, then you could combine toIntOrNull() with the safe call operator and a scope function, for example:

for (str in args) {
    str.toIntOrNull()?.let {
        println("The parsed int is $it")
    }
}

Solution 2 - Kotlin

Actually, there are several ways:

Given:

var numberString : String = "numberString" 
// number is the int value of numberString (if any)
var defaultValue : Int    = defaultValue

Then we have:

Operation Numeric value Non-numeric value
numberString.toInt() number NumberFormatException
numberString.toIntOrNull() number null
numberString.toIntOrNull() ?: defaultValue number defaultValue

If numberString is a valid integer, we get number, else see a result in column Non-numeric value.

Solution 3 - Kotlin

val i = "42".toIntOrNull()

Keep in mind that the result is nullable as the name suggests.

Solution 4 - Kotlin

As suggested above, use toIntOrNull().

> Parses the string as an [Int] number and returns the result > or null if the string is not a valid representation of a number.

val a = "11".toIntOrNull()   // 11
val b = "-11".toIntOrNull()  // -11
val c = "11.7".toIntOrNull() // null
val d = "11.0".toIntOrNull() // null
val e = "abc".toIntOrNull()  // null
val f = null?.toIntOrNull()  // null

Solution 5 - Kotlin

I use this util function:

fun safeInt(text: String, fallback: Int): Int {
    return text.toIntOrNull() ?: fallback
}

Solution 6 - Kotlin

string_name.toString().toInt()

converts string_name to String and then the resulting String is converted to int.

Solution 7 - Kotlin

i would go with something like this.

import java.util.*

fun String?.asOptionalInt() = Optional.ofNullable(this).map { it.toIntOrNull() }

fun main(args: Array<String>) {
    val intArgs = args.map {
        it.asOptionalInt().orElseThrow {
            IllegalArgumentException("cannot parse to int $it")
        }
    }

    println(intArgs)
}

this is quite a nice way to do this, without introducing unsafe nullable values.

Solution 8 - Kotlin

In Kotlin:

Simply do that

val abc = try {stringNumber.toInt()}catch (e:Exception){0}

In catch block you can set default value for any case string is not converted to "Int".

Solution 9 - Kotlin

fun getIntValueFromString(value : String): Int {
    var returnValue = ""
    value.forEach {
        val item = it.toString().toIntOrNull()
        if(item is Int){
            returnValue += item.toString()
        }

    }
    return returnValue.toInt()

}

Solution 10 - Kotlin

add (?) before fun toInt()

val number_int = str?.toInt()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHard CoderView Question on Stackoverflow
Solution 1 - Kotlinearthw0rmjimView Answer on Stackoverflow
Solution 2 - KotlinHoa NguyenView Answer on Stackoverflow
Solution 3 - KotlinGrzegorz PiwowarekView Answer on Stackoverflow
Solution 4 - KotlinCoolMindView Answer on Stackoverflow
Solution 5 - KotlinGoran Horia MihailView Answer on Stackoverflow
Solution 6 - KotlinJames WaltonView Answer on Stackoverflow
Solution 7 - KotlinleetwinskiView Answer on Stackoverflow
Solution 8 - KotlinGhayasView Answer on Stackoverflow
Solution 9 - KotlintherealsanaullahView Answer on Stackoverflow
Solution 10 - KotlinDjalal MesserhiView Answer on Stackoverflow