Why Nested Class is better than Inner Class when I create ViewHolder in RecyclerView

77 Views Asked by At

I heard that inner class use more memory than nested class in Kotlin. And somebody said it is bad for using inner Class in RecyclerView(ViewHolder).

But, It was hard to use onClickListener without inner class.

I can't exactly understand why memory leak happens with inner class in RecyclerView.

And It is must to use nested class rather than inner class? then... what reason inner class exist for? Can somebody tell me answer?

I asked Chatgpt but it only say about memory leak.... I want to understand detail action about it!

1

There are 1 best solutions below

0
Rakib Hasan On

At first you need to know the difference between Inner and Nested Classes

  • Inner classes: Have access to the enclosing class's members (including non-static ones) and capture a reference to the enclosing object instance. This creates a potential for memory leaks if the inner class instance and enclosing object outlive their intended scope.
  • Nested classes: Don't capture an implicit reference to the enclosing object, but can only access static members of the enclosing class. This makes them safer for memory leaks but less flexible.

Also, you need to understand when and why Memory Leaks occur's in RecyclerView.

When you use inner classes as listeners in RecyclerView's ViewHolder, a problem arises if the ViewHolder holds onto the reference to its inner class listener. This extends the lifespan of the ViewHolder beyond its intended scope, even if the RecyclerView removes it from the view hierarchy. The ViewHolder and its inner class listener then keep each other alive in memory, leading to a memory leak.

Again, you don't have to use nested classes always, but they can be handy when you want a closely connected class without access to its non-static parts or to prevent memory issues. Inner classes exist because they help keep related functions organized within a class, can access non-static parts easily, and offer more flexibility in certain situations. So, it's not a must, but they bring some cool benefits!

So, based on your situation, I can suggest you to use Lambda (my personal opinion). See example code snippet bellow -

class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    val textView: TextView = view.findViewById(R.id.text_view)

    init {
        textView.setOnClickListener { position ->
            // Your click handler logic here with access to position
        }
    }
}

Lamda is similar to anonymous classes, lambdas offer a concise way to define listeners without separate classes. This can improve code readability and avoid memory leaks.

Hope it helps!