How to use Kotlin to find whether a string is numeric?

Version 1 (using toIntOrNull and when as requested)

fun String.intOrString(): Any {
    val v = toIntOrNull()
    return when(v) {
        null -> this
        else -> v
    }
}

"4".intOrString() // 4
"x".intOrString() // x

Version 2 (using toIntOrNull and the elvis operator ?:)

when is actually not the optimal way to handle this, I only used when because you explicitly asked for it. This would be more appropriate:

fun String.intOrString() = toIntOrNull() ?: this

Version 3 (using exception handling):

fun String.intOrString() = try { // returns Any
   toInt()
} catch(e: NumberFormatException) {
   this
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)