我在kotlin活动中使用ViewPager,我想在kotlin片段中使用dagger 注射.我有一个错误:dagger 不支持注入私有领域.

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]
        }
    }

我的Kotlin 碎片

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(消息分级构建)

enter image description here

推荐答案

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.


Old answer

移除internal个修饰语.Dagger至少需要包私有访问才能访问带注释的字段.在Kotlin internal中,修饰符not是Java包私有访问修饰符的替代品.

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.

Kotlin相关问答推荐

在Kotlin中将String转换为T

collectAsState 未从存储库接收更改

如何使用multiset与JOOQ获取关联的记录列表?

kotlin中如何使用子类调用父静态方法?

扩展属性委托给实例属性

Android Jetpack Compose:在空的 Compose 活动中找不到 OutlinedTextField (Material3)

Kotlin:伴随对象内的函数扩展

Kotlin spring boot @RequestBody 验证未触发

如何在 Compose 中创建可重用的修饰符?

Kotlin 方法重载

Foo::class.java 和 Foo::javaClass 有什么区别?

Kotlin:找不到符号类片段或其他 android 类

无法为 retrofit2.Call 调用无参数构造函数

Kotlin使用运行时断言进行空判断?

ObjectAnimator.ofFloat 不能直接在kotlin中取Int作为参数

如何在使用Koin DI的活动之间共享同一个ViewModel实例?

Java中lazy的Kotlin类似功能是什么?

将字符串编码为Kotlin中的UTF-8

如何计算Kotlin中的百分比

Kotlin:测试中的 java.lang.NoSuchMethodError