How to convert String to Int in Kotlin?

前端 未结 7 1055
再見小時候
再見小時候 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:13

    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.

    0 讨论(0)
提交回复
热议问题