Inject Kotlin inline class with Dagger/Hilt

Viewed 407

Is there a way to inject instances of a Kotlin inline class with Dagger? In other words is there any way to get this code to compile assuming that we have a Dagger component that includes UserModule?

inline class Username(val name: String)

@Module
class UserModule {

    @Provides
    fun provideUsername(): Username = Username("default_user")
}

class MyClass @Inject constructor(private val username: Username)

I am specifically trying to do this on Android using Hilt. Not sure if that matters or not.

1 Answers

Same here - wanted this instead of injecting a "Named" or class instance wrapper string via Hilt:

@JvmInline
value class ApplicationFlavor @Inject constructor(private val flavor: String) {
    fun isPaid() = flavor.equals("paid", true)
    fun isFree() = flavor.equals("free", true)
    fun trial() = flavor.equals("trail", true)
}

but decided to settle for using a class instance since I couldn't seem to find a workaround:

class ApplicationFlavor...

@Provides
@Singleton
fun provideApplicationFlavor() = ApplicationFlavor(BuildConfig.FLAVOR)
Related