Kotlin Factory on Inner Nested Class -


i trying create nested inner class in kotlin companion object factory method (the equivalent of static factory method in java). here's simplified version of 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 , return view, omitted. need access mydata     } } 

the compilier highlights "companion", saying "modifier companion not applicable inside inner class" , highlights innerclass() call, saying "expression inaccessible nested class factory", use "inner" keyword make class inner.

how can achieve i'm trying here equivalent of static factory method in java?

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 following will not compile in kotlin:

class parent {     inner class nested {         companion object factory {          }     } } 

for same reasons following will not compile in java:

public class parent {     public class nested {         public static boolean create(){             return false;         }     } } 

the culprit here nested inner classes in kotlin, nested non static classes in java have implicit reference parent class instance. since kotlin aims highly interoperable java follows same rule.

please see following questions more in-depth explanation:


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -