Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guice TypeLiterals in Kotlin

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

like image 400
evad3 Avatar asked Mar 13 '18 16:03

evad3


1 Answers

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)
like image 118
hotkey Avatar answered Nov 20 '22 17:11

hotkey