Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Providing a generic instance in Kotlin & Guice

Tags:

kotlin

guice

I have a Guice Module that provides a List<String> using a @Provides-annotated method.

class TestModule() : Module {
  override fun configure(binder: Binder) {}
  @Provides fun getStrings(): List<String> = listOf("foo", "bar")
}

class Test {
  @Test fun `provider can not deliver`() {
    val injector = Guice.createInjector(TestModule())
    injector.getInstance(object : Key<List<String>>() {})
  }
}

The test, however, fails with:

1) No implementation for java.util.List<? extends java.lang.String> was bound.
  while locating java.util.List<? extends java.lang.String>

Now, this seems to be the same as this question but I have no idea where to add the @JvmSuppressWildcards annotation; adding it to the getStrings() method doesn’t change anything, as does adding it to the object in the getInstance() call. How do I get Guice to do what I want?

like image 225
Bombe Avatar asked Feb 04 '17 09:02

Bombe


1 Answers

After lots of trial and error I arrived at this solution:

@Test
fun `provider can not deliver`() {
  val injector = Guice.createInjector(TestModule())
  injector.getInstance(object : Key<List<@JvmSuppressWildcards String>>() {})
}

It’s the last place I would have thought that the annotation is actually valid but suddenly the test was green.

like image 63
Bombe Avatar answered Oct 01 '22 08:10

Bombe