Convert String obtained from edittext to Integer in Kotlin language

后端 未结 3 1890
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 16:20

I am trying to make a simple Android application using Kotlin language. I have one EditText, I am getting its value in String but I want to convert that value into an intege

3条回答
  •  误落风尘
    2020-12-17 17:17

    You can use .toInt():

    val myNumber: Int = "25".toInt()
    

    Note that it throws a NumberFormatException if the content of the String is not a valid integer.

    If you don't like this behavior, you can use .toIntOrNull() instead (since Kotlin 1.1):

    val myNumOrNull: Int? = "25".toIntOrNull()
    

提交回复
热议问题