Inner class can be a static nested classKT-R1001
When you declare a nested class with the inner
keyword, it becomes an inner class. Inner classes have a reference to the
instance of the outer class that created them. As a result, they can access both the member properties and functions of
the outer class. Inner classes are tightly bound to the instances of the outer class.
On the other hand, when you declare a nested class without the inner
keyword, it becomes a static nested class. Static
nested classes do not have a reference to the instance of the outer class. They are essentially like regular classes declared
outside the outer class, except they are scoped within the outer class namespace.
If a nested class does not access any members from the outer class, it does not need the inner
qualifier, and it should
be refactored to a static nested class. This ensures that the nested class does not hold any reference to the outer class
instance, reducing memory usage and potential memory leaks.
Bad Practice
class A {
val foo = "BAR"
// `B` does not access `foo`, the only member of the outer class `A`.
// Therefore, `B` can be refactored into a static nested class.
inner class B {
val fizz = "BUZZ"
fun printFizz() {
println(fizz)
}
}
}
Recommended
Remove the inner
qualifier to convert the class into a static nested class.
class A {
val foo = "BAR"
class B {
val fizz = "BUZZ"
fun printFizz() {
println(fizz)
}
}
}