Issue
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.
Solution
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
}
Answered By - Willi Mentzel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.