How can I covert String to Int in Kotlin and if it can't be then return 0 (default value).
I think the best solution is to tell value is Int and use Elvis operator to assign value 0 if it can't be converted.
val a:String="22"
val b:Int = a.toIntOrNull()?:0//22
val c:String="a"
val d:Int = c.toIntOrNull()?:0//0
To make code more concise you can create Extension Function
fun String?.toIntOrDefault(default: Int = 0): Int {
return this?.toIntOrNull()?:default
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With