我无法从 Kotlin 中的嵌套类访问任何类成员 [英] I can't reach any class member from a nested class in Kotlin

查看:43
本文介绍了我无法从 Kotlin 中的嵌套类访问任何类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 PersonAdapter 类访问 MainFragment 类的一个成员,但它们都不可用.我尝试将班级和成员设为公开和私有,但到目前为止没有任何效果.我想我错过了一些明显的东西,但我就是想不通.

I want to access a member of the MainFragment class from PersonAdapter class but none of them are available. I tried making both the classes and the members public and private also but so far nothing worked. I guess I'm missing something obvious but I just can't figure it out.

class MainFragment : Fragment() {
    lateinit var personAdapter: PersonAdapter
    lateinit var personListener: OnPersonSelected
    private var realm: Realm by Delegates.notNull()
    lateinit var realmListener: RealmChangeListener<Realm>

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val v = inflater.inflate(R.layout.fragment_main, container, false)
        return v
    }

    class PersonAdapter() : RecyclerView.Adapter<ViewHolder>() {
        var localPersonList = personList

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder.bindItems(localPersonList[position])

            holder.itemView.setOnClickListener {
                Toast.makeText(context, "click", Toast.LENGTH_SHORT).show()
                //I want to reach personListener from here
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
            val v = LayoutInflater.from(parent!!.context).inflate(R.layout.person_list_item, parent, false)
            return ViewHolder(v)
        }
    }}

推荐答案

在 Kotlin 中,嵌套类默认无法访问外部类实例,就像嵌套的 static class 在 Java 中不能访问一样.

In Kotlin, nested classes cannot access the outer class instance by default, just like nested static classes can't in Java.

为此,将 inner 修饰符添加到嵌套类:

To do that, add the inner modifier to the nested class:

class MainFragment : Fragment() {
    // ...

    inner class PersonAdapter() : RecyclerView.Adapter<ViewHolder>() {
        // ...
    }
}

请注意,inner 类持有对其包含类实例的引用,这可能会影响后者的生命周期,并且如果 inner 类可能会导致内存泄漏实例是全局存储的.

Note that an inner class holds a reference to its containing class instance, which may affect the lifetime of the latter and potentially lead to a memory leak if the inner class instance is stored globally.

请参阅:语言中的嵌套类参考

See: Nested classes in the language reference

这篇关于我无法从 Kotlin 中的嵌套类访问任何类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆