'Parse String to another appropriate type
I have some code where I can receive, depending on the case: a text , an integer (381) or a decimal (431.2).
They are all coming as a string.
How can I parse them to String, Int or Double as needed?
Solution 1:[1]
Something like this should help:
fun checkContentType(): Any {
val data: String = "12.3";
val ir = data.toIntOrNull();
if( ir != null ) return ir;
val dr = data.toDoubleOrNull();
if( dr != null ) return dr;
return data;
}
Also, as @gidds said, another approach would be to extend the String class and then use the Elvis operator like this:
fun String.convertToAppropriateType() = toIntOrNull() ?: toDoubleOrNull() ?: this
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | S. Dre |
