How to convert String to Int in Kotlin?

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

    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: Int? = "11".toIntOrNull()   // 11
    val b: Int? = "-11".toIntOrNull()  // -11
    val c: Int? = "11.7".toIntOrNull() // null
    val d: Int? = "11.0".toIntOrNull() // null
    val e: Int? = "abc".toIntOrNull()  // null
    val f: Int? = null?.toIntOrNull()  // null
    

提交回复
热议问题