https://kotlinlang.org logo
#android
Title
# android
a

AmrJyniat

07/30/2022, 11:11 AM
Is there a
findOr
fun like
find{}
in Kotlin collections but let me do another thing if the result was null?
p

Paul Woitaschek

07/30/2022, 1:13 PM
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

AmrJyniat

07/30/2022, 1:22 PM
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

Paul Woitaschek

07/30/2022, 1:27 PM
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

Zun

07/30/2022, 8:33 PM
What about “devices.any { it in listOfEnums }”
p

Paul Woitaschek

07/31/2022, 8:14 AM
That original algorithm has a prioritization and prefers Bluetooth over wired over earpieces.
h

hfhbd

07/31/2022, 11:18 AM
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
14 Views