Is there any way to "pin" generics to another type...
# general-advice
c
Is there any way to "pin" generics to another type? Like have a
Map<Class<T>, Supplier<T>>
, where
T
is NOT a type parameter of the enclosing class but instead "pinning" the type of the supplier to the type of the class for runtime type validation? Instead of
Map<Class<*>, Supplier<*>>
and having to suppress constant type coercion warnings
s
I think a typealias would do the trick:
Copy code
typealias MyThing<T> = Map<Class<T>, Supplier<T>>
c
I'm trying to specify that the type T is the same only for each individual entry, but different between different entries
s
Oh, I understand
c
For example, if I tell the map
get(Foo::class)
, I know that the result will always be a
Supplier<Foo>
, but there's no way to specify that I know of
👍 1
s
You can't do it with a regular
Map
, and I don't know of any other built-in type that does it, but it's easy enough to express it in the type system:
Copy code
interface SupplierMap {
  fun <T> get(type: KClass<T>): Supplier<T>
}
1