```open class Human() class Men:Human() class Wom...
# announcements
d
Copy code
open class Human() 
class Men:Human()
class Women:Human()
val humanNation = asList(Women(), Man())
val womenForMe = humanNation.firstOrNull{ it is Women} as Women?
any shorter form? thank you @agrosner for the help the solution is
inline fun <reified K:T, T> List<T>.firstOrNull(): K? = firstOrNull { it is K} as K?
usage
val womenForMe : Women = humanNation.firstOrNull()
🤨 2
z
I don't think you need the cast to
Women?
a
It might return a base class that's why he's casting
👆 3
f
there's
filterIsInstance
but that's not shorter and will go through the whole list
s
I assumed there was some base
Human
type that was being implemented
👏 1
k
not with a sequence and
.first()
a
Make an extension inline reified method
Then you can just call firstOrNull<Woman>
like this:
Copy code
inline fun <reified T> List<T>.singleOrNull(): T? = singleOrNull { it is T} as T?
that might work. not sure what kind of object you're operating on
d
let me check, it could be a solution
nope it doesn't help much as it should operate on Human and Women:Human class, like <T:K, K>
ok, got it, thx @agrosner using your solution I found the way,
inline fun <reified K:T, T> List<T>.firstOrNull(): K? = firstOrNull { it is K} as K?
a
great!