can anyone think of a more idiomatic (but readable...
# announcements
t
can anyone think of a more idiomatic (but readable) way of writing this?
Copy code
for (entry in map) {
    if (myValue.startsWith(entry.key)) {
        myAction()
        return true
    }
}
return false
👍 1
c
if (map.any { myValue.startsWith(it)} …
k
return map.find { (k,v) -> myValue.startsWith(k) } ?. also { myAction() } != null
c
also
instead of
let
then it does not matter what the block returns
👍 1
t
thanks, do you think it's more readable though?
i would prefer karels suggestion, but there's no find on map
could filter though
but that
also
just looks tacked on 🤔
i had
map.any { myValue.startsWith(it.key) && doAction() }
at one point, which seems very hacky, but i actually find it more readable than the
also
c
does doAction need the found value?
imo you should use an if, to make it explicit whats happening
map.any {…&& doAction() }
is just wrong
💯 1
if you do it that way use
forEach
or
map
. because its just a side effect that
any
executes the block on every entry in the map
t
any should return immediately after the first matching element 🤔
i think i will just keep the old fashioned imperative approach in this case
👎 1
k
You can do
map.entries.find { ... }
then.
c
or any, but do the action outside of the block
t
do you really think it's more readable @karelpeeters ?
k
The
also
is maybe a stretch but the find it a lot better IMO.
t
but you're returning a
find
also
!= null
i don't know, i found it very hard to read
the imperative version is verbose, but straightforward
k
Well if you don't care about the actual value of course use
any
and an if on the result.