Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

types

kotlin

I'd like to use a when() expression in Kotlin to return different values from a function. The input is a String, but it might be parsable to an Int, so I'd like to return the parsed Int if possible, or a String if it is not. Since the input is a String, I cannot use the is type check expression.

Is there any idiomatic way to achieve that?

My problem is what the when() expression should look like, not about the return type.

like image 868
uzilan Avatar asked Jan 05 '18 15:01

uzilan


People also ask

How do I check if a string is numeric in Kotlin?

To check if string contains numbers only, in the try block, we use Double 's parseDouble() method to convert the string to a Double . If it throws an error (i.e. NumberFormatException error), it means string isn't a number and numeric is set to false . Else, it's a number.

How do you check if a value is a string or integer?

We can use the isdigit() function to check if the string is an integer or not in Python. The isdigit() method returns True if all characters in a string are digits. Otherwise, it returns False.


5 Answers

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
}
like image 92
Willi Mentzel Avatar answered Oct 23 '22 12:10

Willi Mentzel


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

like image 37
rdurand Avatar answered Oct 23 '22 14:10

rdurand


Using let for one

fun isInteger(str: String?) = str?.toIntOrNull()?.let { true } ?: false
like image 9
Linh Pham Avatar answered Oct 23 '22 13:10

Linh Pham


Simple and intuitive

fun isNumeric(str: String) = str.all { it in '0'..'9' }

As @coolMind point out, if you want to filter +/-

fun isNumeric(str: String): Boolean = str
        .removePrefix("-")
        .removePrefix("+")
        .all { it in '0'..'9' }

The performance would be similar

like image 7
Haram1436 Avatar answered Oct 23 '22 13:10

Haram1436


If you want to check if it is numeric (Int) the string and do something a simple solution could be:

if (myString.toIntOrNull() != null) {
   //Write your code you want to execute if myString is (Int)
} else {
   //Write your code you want to execute if myString is (not Int)
}
like image 4
F.Mysir Avatar answered Oct 23 '22 13:10

F.Mysir