AmrJyniat
07/30/2022, 11:11 AMfindOr
fun like find{}
in Kotlin collections but let me do another thing if the result was null?Paul Woitaschek
07/30/2022, 1:13 PMusers.findOrElse({ it.name == "Alice" }) {
Person("alice")
}
AmrJyniat
07/30/2022, 1:22 PMval 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 cleanerPaul Woitaschek
07/30/2022, 1:27 PMfun <T : Any> List<T>.multiFind(vararg predicates: (T) -> Boolean): T? {
predicates.forEach { predicate ->
find(predicate)?.let { return it }
}
return null
}
😉devices.maxByOrNull {
when(it) {
is bluetooth -> 3
is wired -> 2
is earpiece -> 1
}
}
Zun
07/30/2022, 8:33 PMPaul Woitaschek
07/31/2022, 8:14 AMhfhbd
07/31/2022, 11:18 AMvar 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