Issue
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 would 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 String class and using Elvis operator like this :
fun String.convertToAppropriateType() = toIntOrNull() ?: toDoubleOrNull() ?: this
Answered By - nullqube
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.