Search code examples
kotlinvariable-types

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

  • 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