Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Parent class variables in companion Object in Kotlin

Tags:

android

kotlin

I am trying to call static function of one class in other like java , But in kotlin I can not make a static function , and I have to make a companion object in which I have to define my function , But while doing this I am not able to access parent class variables , is there any way I can achieve this in kotlin .

class One {

    val abcList = ArrayList<String>()

    companion object {

        fun returnString() {
            println(abcList[0]) // not able to access abcList here
        }
    }
}

class Two {

    fun tryPrint() {
        One.returnString()
    }
}
// In Java we can do it like this

class One {

    private static ArrayList<String> abcList = new ArrayList<>();

    public void tryPrint() {
        // assume list is not empty 
        for(String ab : abcList) {
            System.out.println(ab);
        }
    }

    public static void printOnDemand() {
        System.out.println(abcList.get(0));
    }
}

class Two {

    public void tryPrint(){
        One.printOnDemand();
    }
}

I want to access fun returnString() like static function of class one like we do in java , if any one have achieved this please help .

like image 687
Danial clarc Avatar asked Aug 27 '19 11:08

Danial clarc


2 Answers

In your case abcList is a member variable of the class. Each instance of a class has their own version of its member variables which means that a static method cannot access them. If you want to access it from your companion object it has to be static too.

class One {
    companion object {
        val abcList = ArrayList<String>()

        fun returnString() {
            println(abcList[0])
        }
    }
}

class Two {
    fun tryPrint() {
        One.returnString()
    }
}

This code will work, but keep in mind that in this case there will be only one instance of abcList. Accessing a member variable from a static function is not possible (not even in Java).

Here's the Kotlin version of your Java example:

class One {
    companion object {
        val abcList = ArrayList<String>()

        fun printOnDemand() {
            println(abcList[0])
        }
    }

    fun tryPrint() {
        for (ab in abcList) {
            println(ab)
        }
    }
}

class Two {
    fun tryPrint() {
        One.printOnDemand()
    }
}
like image 142
pshegger Avatar answered Oct 27 '22 00:10

pshegger


Rule: You can't access static properties, members of a class in none static members and you can't access none static properties, members of a class in static members which is the companion object class. This rule is in both Java and Kotlin. If you want to access a none static member of a class inside static members you have to declare it inside companion object class.

like image 22
Meraj Avatar answered Oct 27 '22 00:10

Meraj