'How to check string has digit only in kotlin
Hey I working in kotlin android. The string is coming from server and it might be contains digit, character, empty string or null value. I want to convert that value in double because I want to compare value. So is there any better way to check that string only contain digit value and not empty or null in a kotlin way. The list is huge so I want a efficient way.
Price.kt
data class Price(
var value: String? = null
)
main.kt
val defaultValue : Double = 4.23
val list = listOf(Price("2.33"), Price("fr23"), Price(""), Price(null), Price("4.23"), Price("12.23"))
list.forEach{
if(it == defaultValue){
println("Found It")
}
}
Solution 1:[1]
Kotlin already has an efficient solution: toDoubleOrNull
Parses the string as a Double number and returns the result or null if the string is not a valid representation of a number.
if (list.any { it.value.toDobleOrNull() == defaultValue }) {
println("Found It")
}
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 | bylazy |
