How to convert String to Int in Kotlin?

2019-04-21 02:39发布

问题:

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?

回答1:

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")
    }
}


回答2:

val i = "42".toIntOrNull()

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



回答3:

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:

+—————————————————————————————————————————————+——————————+———————————————————————+
| numberString is a valid number ?            |  true    | false                 |
+—————————————————————————————————————————————+——————————+———————————————————————+
| numberString.toInt()                        |  number  | NumberFormatException |
+—————————————————————————————————————————————+——————————+———————————————————————+
| numberString.toIntOrNull()                  |  number  | null                  |
+—————————————————————————————————————————————+——————————+———————————————————————+
| numberString.toIntOrNull() ?: defaultValue  |  number  | defaultValue          |
+—————————————————————————————————————————————+——————————+———————————————————————+


回答4:

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.



标签: kotlin