Is there a `findOr` fun like `find{}` in Kotlin co...
# android
a
Is there a
findOr
fun like
find{}
in Kotlin collections but let me do another thing if the result was null?
p
I don’t think there is as it wouldn’t provide much benefit over doing a ?:
I can’t see where that would be useful
Copy code
users.findOrElse({ it.name == "Alice" }) {
  Person("alice")
}
a
Copy code
val rightDevice = devices.find { it is AudioDevice.BluetoothHeadset 
} ?: 
devices.find { it is AudioDevice.WiredHeadset 
} ?:
devices.find { it is AudioDevice.Earpiece }
Trying to make this code a bit cleaner
p
That looks pretty clean to me already
👍 1
Copy code
fun <T : Any> List<T>.multiFind(vararg predicates: (T) -> Boolean): T? {
  predicates.forEach { predicate ->
    find(predicate)?.let { return it }
  }
  return null
}
😉
Ah or better: Go with a sorting!
Copy code
devices.maxByOrNull {
  when(it) {
    is bluetooth -> 3
    is wired -> 2
    is earpiece -> 1
  }
}
z
What about “devices.any { it in listOfEnums }”
p
That original algorithm has a prioritization and prefers Bluetooth over wired over earpieces.
h
In theory, you could also iterate only once: return if bluetooth found or store the first wired and the first earpiece. and return wired ?: earpiece 🙂
Copy code
var wired: Device? = null
var earpiece: Device?  = null
for (device in devices) {
  if (device is Bluetooth) { return device }
  if (device is Wired && wired == null) { wired = device }
  if (device is EarPiece && earpice == null) { earpiece = device }
}
return wired ?: earpiece
Even better with a sealed class and when