what would be a nice way to implement a keyTypeMap...
# getting-started
m
what would be a nice way to implement a keyTypeMap. Something like
Map<KClass<out T>, SomeType<T>>
currently we are filtering from a list in multiple factories which is an O(factories * N) problem. Ideally I just want to request a class type from a map and get the correct implementation
t
I suggest writing some (non-Map) type that uses some regular Map in the background and handles the type casting for you. you could even write
reified
overloads of
get
and
set
, so you wouldn't even need to put the class object in the arguments (depending on your use case). A real
Map
implementation will probably not work, at least not with the default get and put methods, because you can't override the interface methods with one that requires generics. Here is an example implementation: https://pl.kotl.in/A2tG9y92U
👍 1
m
Looks great Tobias! The solution was indeed a simple wrapper. I had my mind set on a map implementation
e
the Map interface can't express this. stdlib itself has what is effectively a typed map:
kotlin.coroutines.CoroutineContext
associates from
Key<Element>
to
Element
. there's a few other projects out there like https://github.com/broo2s/typedmap. but if you just want a class->instance map, something simple like that example is fine.
blob thinking fast 1
j
You could also look at how the coroutine context map is implemented. It's basically a typed heterogeneous map like you're looking for. Maybe slightly more complicated than the example here
e
I don't think CoroutineContext as a typed map is a reasonable thing to copy unless you're building something just like it, because there's no explicit Map; it's built up from
+
and composition of various `Element`s each of which will handle
get
of its own key or delegate to the next context
👍 1