Parse String to another appropriate type

180 Views Asked by At

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?

1

There are 1 best solutions below

1
On BEST ANSWER

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