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?