I use in kotlin activity ViewPager and I want in Kotlin Fragment use the dagger injection. I have got Error: Dagger does not support injection into private fields. In Java Fragment the dagger injection work. Why can i not inject dagger in kotlin faragment ?
in my kotlin activity
mPagerAdapter = object : FragmentPagerAdapter(supportFragmentManager) { private val mFragments = arrayOf(KotlinFragment(), JavaFragment()) private val mFragmentNames = arrayOf(getString(R.string.cashdocuments), getString(R.string.action_absmysql)) override fun getItem(position: Int): Fragment { return mFragments[position] } override fun getCount(): Int { return mFragments.size } override fun getPageTitle(position: Int): CharSequence { return mFragmentNames[position] } }
my kotlin fragment
class KotlinFragment : Fragment() { @Inject internal var mSharedPreferences: SharedPreferences? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (activity.application as SamfantozziApp).dgaeacomponent().inject(this) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) val rootView = inflater!!.inflate(R.layout.activity_absserver, container, false) return rootView } }
messages gradle build
Dagger cannot support private fields and still support code-generated adapters (to avoid reflection). The way systems like Guice support private fields is they change the access to the field reflectively before accessing them.
Dagger is a fully static, compile-time dependency injection framework for Java, Kotlin, and Android.
You have mistake here:
@Inject internal var mSharedPreferences: SharedPreferences? = null
This looks like you added @Inject
annotation to the KotlinFragment
class
Please change it to this and it will work:
var mSharedPreferences: SharedPreferences? = null @Inject set
Here is the link to the documentation: https://kotlinlang.org/docs/reference/annotations.html
Accidentally I came across to my own answer and have to confess, that in fact it isn't working (at least for my use-case). Please consider Avilio's answer which worked for me also: substitute internal
with lateinit
.
Remove internal
modifier. Dagger needs at least package-private access in order to access annotated field. In Kotlin internal
modifier is not a substitution for Java's package-private access modifier.
For detailed explanation of differences between modifiers in Java and Kotlin refer to Fragmented podcast's episode #101 - "Learning Kotlin – visibility modifiers, internal modifier, modules", as well as the official docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With