Reputation: 5931
So I'm new to kotlin and was looking for a way to express an if condition with it's action in a more idiomatic way. So I have an object that behaves like a collection so I can call any/filter on it. Basically I want to check if that collection has a specific key, and if it has, I want to check then if the value is the one I'm expecting. If both conditions are true, I want to apply some action.
I guess I could just write:
exists = collection.any() { item ->
item.key() == "mykey" && item.value() == "myvalue"
}
if(exists) {
// do something
}
Is there a better way to write the above code in Kotlin ?
Upvotes: 1
Views: 517
Reputation: 1139
If you want to use the element right when you find it, you could say:
collection.first { it.key == "myKey" && it.value == "myValue" }
.let {
// Do something with it here
println("Found: $it")
}
Note the use of it
saves some typing and is good as long as one can tell what it is from looking at the expresion.
Also first()
returns the element or an exception if not found, so consider firstOrNull()
if it is possible no elemente will satisfy the condition.
If you're only interested in the mere existence or not of the element then is probably better:
if (collection.any { it.key == "myKey" && it.value == "myValue" }) {
// Do something
}
If your predicate gets complicated, move it into a function:
fun code() {
if (collection.any(::predicate)) {
// Do something
}
}
private fun predicate(it: Item) =
it.key == "myKey" && it.value == "myValue"
Upvotes: 0
Reputation: 1934
I wouldn't overthink it. I think something like this is more readable:
if (collection["myKey"] == "myValue") {
// do something
}
Note that collection["myKey"]
has an optional return type, so if your key isn't in the collection it would return null
. This is going off the idea that your collection is very similar to a map or set as both would return null
for an undefined element.
Upvotes: 3