8

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

1 Answer 1

12

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

I just want to add to this that it compiles as above - however remember to add @JvmSuppressWildcards on the injection points and the declaration For example bind(object : TypeLiteral<Resolver<@JvmSuppressWildcards RealObject>>() { }).to..... Then to implement class InjectionTest @Inject constructor(resolver: Resolver<@JvmSuppressWildcards RealObject>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.