I am trying to create a nested inner class in Kotlin with a companion object factory method (the equivalent of a static factory method in Java). Here's a simplified version of my code.
class OuterClass {
var myData:List<MyData> = List<>() //gets populated elsewhere
fun getItemFragment(position:Int) : Fragment() {
return InnerClass.Factory.newInstance(position)
}
inner class InnerClass : Fragment() {
companion object Factory {
fun newInstance(position:Int) : InnerClass {
var ic : InnerClass = InnerClass()
var bundle:Bundle = Bundle()
bundle.putInt("index", position)
ic.arguments = bundle
return ic
}
}
override fun onCreateView(inflater:LayoutInflater, container: ViewGroup, savedInstanceState:Bundle): View? {
//create and return view, omitted. Need access to myData
}
}
The compilier highlights "companion", saying "Modifier companion is not applicable inside inner class" and it also highlights the InnerClass() call, saying "Expression is inaccessible from a nested class Factory", use "inner" keyword to make the class inner.
How can I achieve what I'm trying to do here with the equivalent of a static factory method in Java?
Inner class cannot be declared inside interfaces or non-inner nested classes. The advantage of inner class over nested class is that, it is able to access members of outer class even it is private. Inner class keeps a reference to an object of outer class.
Kotlin Inner Class When we can declare a class inside another class using the keyword inner then it is called inner class. With the help of the inner class, we can access the outer class property inside the inner class.
class Outer { class Inner { void someMethod() { Outer. super. someOtherMethod(); } } @Override public String someOtherMethod() { // This is not called... } }
Anonymous inner class instances are created using an object expression: window. addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { ... } override fun mouseEntered(e: MouseEvent) { ... } })
You can have:
class OuterClass {
fun getItemFragment(position: Int): Fragment {
return InnerClass.Factory.newInstance(position)
}
class InnerClass : Fragment() {
companion object Factory {
fun newInstance(position: Int): InnerClass {
var ic: InnerClass = InnerClass()
return ic
}
}
}
}
However the following will not compile in Kotlin:
class Parent {
inner class Nested {
companion object Factory {
}
}
}
For the same reasons the following will not compile in Java:
public class Parent {
public class Nested {
public static boolean create(){
return false;
}
}
}
The culprit here is that nested inner
classes in Kotlin, as well as nested non static classes in Java have an implicit reference to parent class instance. Since Kotlin aims to be highly interoperable with Java it follows the same rule.
Please see following questions for more in-depth explanation:
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