Hi, How can I create this extension function sortB...
# android
s
Hi, How can I create this extension function sortByStringValue? I have a list that can contain strings or numbers as strings. Sorting won’t work correctly if the string contain numbers. If I have a selector that can return String or Double it’s not accepted. Any good workaround?
Copy code
val list = mutableListOf<String>("10", "0.1", "0.01", "1")
        list.sortBy { // default kotlin in-place sorter
            it
        }
        list.sortByStringValue {
            if (it.toDoubleOrNull() == null) {
                it
            } else {
                it.toDouble()
            }
        }
j
Copy code
val list = listOf("10", "0.1", "0.01", "1")

list.sortByStringValue()

fun List<String>.sortByStringValue() = mapNotNull(String::toDoubleOrNull).sorted()
output:
Copy code
[0.01, 0.1, 1.0, 10.0]
#codereview for the next ones, this is not related to Android 🙂
👌 1
s
ok thanks but that will only work for numbers
it can have standard Strings, names, descriptions…
I got it
💡
Copy code
fun List<String>.sortByStringValue(): List<String> {
    if (size > 1) {
        return if (first().toDoubleOrNull() == null) {
            sortedBy { it }
        } else {
            sortedBy { it.toDoubleOrNull() }
        }
    }
    return this
}
j
why are you checking the first one
which can't be null, because size > 1
s
yes
j
if strings and numbers are mixed, your algorithm is just thinking in the first item
so it will do random things
s
in this case, if the first item is a number all the others will be numbers
will be safe
just wanted to abstract some code out of the way