I have some listeners: `typealias Listener<T&gt...
# announcements
z
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
Use a map like
Copy code
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
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
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