anvil icon indicating copy to clipboard operation
anvil copied to clipboard

K2 factory generation: don't unwrap generic types in IR

Open RBusarow opened this issue 11 months ago • 0 comments

Given this test:

compile2(
  """
  package com.squareup.test
  
  import dagger.Lazy
  import javax.inject.Inject
  import javax.inject.Provider
  
  class InjectClass @Inject constructor(
    val string: String, 
    val stringProvider: Provider<String>,
    val stringListProvider: Provider<List<String>>,
    val lazyString: Lazy<String>
  ) {
    override fun equals(other: Any?): Boolean {
      return toString() == other.toString()
    }
    override fun toString(): String {
     return string + stringProvider.get() + 
         stringListProvider.get()[0] + lazyString.get()
    }
  }
  """,
) {
  val factoryClass = classLoader.injectClass_Factory
  val staticMethods = factoryClass.declaredMethods.filter { it.isStatic }

  val factoryInstance = staticMethods.single { it.name == "create" }
    .invoke(
      null,
      Provider { "a" },
      Provider { "b" },
      Provider { listOf("c") },
      Provider { "d" },
    )
  assertThat(factoryInstance::class.java).isEqualTo(factoryClass)

  val newInstance = staticMethods.single { it.name == "newInstance" }
    .invoke(null, "a", Provider { "b" }, Provider { listOf("c") }, Lazy { "d" })
  val getInstance = (factoryInstance as Factory<*>).get()
}

The call to factoryInstant.get() will fail:

java.lang.ClassCastException: class java.lang.String cannot be cast to class javax.inject.Provider (java.lang.String is in module java.base of loader 'bootstrap'; javax.inject.Provider is in unnamed module of loader 'app')

RBusarow avatar Feb 20 '25 22:02 RBusarow