问题
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 can not use the is type check expression.
Is there any idiomatic way to achieve that?
Edit: My problem is how the when()
expression should look like, not about the return type.
回答1:
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
}
回答2:
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
回答3:
Using let for one
fun isInteger(str: String?) = str?.toIntOrNull()?.let { true } ?: false
来源:https://stackoverflow.com/questions/48116753/how-to-use-kotlin-when-to-find-if-a-string-is-numeric