munHunger
munHunger

Reputation: 2999

any type with specific parameter

I want to write a kotlin function that can filter lists.

The filtering I want to do is pretty much an ID whitelisting, so imagine that I have a list of string IDs that are allowed. Then the function should remove all objects of the input list that have an ID not in the whitelist. Pretty basic stuff really.

The problem I guess is that I want it really generic. And I am wondering if it is possible in kotlin to take in a list of Any, but that have a property id? Or is it only possible by creating an interface that all objects need to implement?

Upvotes: 0

Views: 52

Answers (1)

findusl
findusl

Reputation: 2644

fun <T> List<T>.filterUnknownIds(getId: T.() -> String): List<T> = filter { it.getId() in whitelistedIds }

Assuming whitelistedIds is a list of strings. I didn't compile the code as I'm on mobile but should work.

Upvotes: 1

Related Questions