How to convert String to Int in Kotlin?

前端 未结 7 1070
再見小時候
再見小時候 2020-12-15 02:30

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

fun main(args: Array) {
    /         


        
7条回答
  •  盖世英雄少女心
    2020-12-15 03:12

    You could call toInt() on your String instances:

    fun main(args: Array) {
        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")
        }
    }
    

提交回复
热议问题