I have a scenario where I have a generic interface and wish to bind multiple implementations of that interface in Guice. Normally in Java this would mean TypeLiterals, how would this be done in Kotlin?
bind(TypeLiteral<Resolver<RealObject>>(){}).to(RealResolver::class.java)
This gives a compiler error of:
cannot access <init>: it is public/*package*/ in 'TypeLiteral'
There is a TypeLiteral.get() method however I cannot seem to get that to work either
Instead of the Java anonymous class syntax (new TypeLiteral<Resolver<RealObject>>(){}
), you should use the Kotlin object expression:
bind(object : TypeLiteral<Resolver<RealObject>>() { }).to(RealResolver::class.java)
You can wrap that into an inline function with a reified type parameter:
inline fun <reified T> typeLiteral() = object : TypeLiteral<T>() { }
Then use it as:
bind(typeLiteral<Resolver<RealObject>>()).to(RealResolver::class.java)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With