Use a try-catch block to gracefully handle exceptions and return a default value in a concise Kotlin function.

fun parseInt(value: String): Int {
    return try {
        value.toInt()
    } catch (e: NumberFormatException) {
        -1
    }
}

Usage:

val result = parseInt("42")
Share this post