Skip to content

Instantly share code, notes, and snippets.

@mitchtabian
Last active July 3, 2020 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitchtabian/9d88bce861d1cfc21d590819781ff6e1 to your computer and use it in GitHub Desktop.
Save mitchtabian/9d88bce861d1cfc21d590819781ff6e1 to your computer and use it in GitHub Desktop.
Basics #5: Some things can't be constructor-injected. What is the solution?

From the Hilt-Android docs:

Sometimes a type cannot be constructor-injected. This can happen for multiple reasons. For example, you cannot constructor-inject an interface. You also cannot constructor-inject a type that you do not own, such as a class from an external library. In these cases, you can provide Hilt with binding information by using Hilt modules.

source: Hilt Modules

Not being able to constructor inject an interface is shown in the example below. Not being able to inject a class that you do not own can't even be shown in an example. You just can't do it because you can't even annotate the class with @Inject. It's impossible because you don't have access to it.

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject
lateinit var someClass: SomeClass
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
println(someClass.doAThing())
}
}
class SomeClass
@Inject
constructor(
private val someInterfaceImpl: SomeInterface
){
fun doAThing(): String{
return "Look I got: ${someInterfaceImpl.getAThing()}"
}
}
class SomeInterfaceImpl
@Inject
constructor(): SomeInterface {
override fun getAThing() : String{
return "A Thing"
}
}
interface SomeInterface{
fun getAThing(): String
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment