https://kotlinlang.org logo
Title
z

ziggy42

03/19/2018, 12:11 PM
I have some listeners:
typealias Listener<T> = (T) -> Unit
and for each
T
that I accept I need to store the list of registered listeners:
val userListeners = mutableListOf<Listener<User>>()
. But this forces me to have N lists for N possible
T
. Is there a better way?
s

spand

03/19/2018, 12:22 PM
Use a map like
data class UserTypeKey(val user: User, val type: Type)

val listenerMap = mutableMapOf<UserTypeKey, Listener>()
But depends on how you need to query it and if it is fast enough to perform a linear scan
z

ziggy42

03/19/2018, 12:26 PM
Mmm sorry but I don't understand. I need the type in Listener, right? How can I say something like
mutableMapOf<T, Listener<T>>()
?
a

Andreas Sinz

03/19/2018, 12:42 PM
you can use a
Map<KClass<*>, MutableList<Function<Unit>>>
and then based on the
T::class
you can retrieve the list of Listeners, but that involves unsafe casts