How to use Kotlin when to find if a string is numeric?

Using let for one

fun isInteger(str: String?) = str?.toIntOrNull()?.let { true } ?: false

Version 1 (using toIntOrNull and when 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 explicitely 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
}

The toIntOrNull function in the kotlin.text package (in kotlin-stdlib) is probably what you're looking for:

toIntOrNull

fun String.toIntOrNull(): Int? (source)

Platform and version requirements: Kotlin 1.1

Parses the string as an Int number and returns the result or null if the string is not a valid representation of a number.

fun String.toIntOrNull(radix: Int): Int? (source)

Platform and version requirements: Kotlin 1.1

Parses the string as an Int number and returns the result or null if the string is not a valid representation of a number.

More information: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/to-int-or-null.html

Tags:

Kotlin