首页 > 解决方案 > 在 Kotlin 中访问伴随对象中的父类变量

问题描述

我正在尝试在其他类中调用一个类的静态函数,例如 java,但是在 kotlin 中我不能创建静态函数,我必须创建一个伴随对象,我必须在其中定义我的函数,但是这样做时我不是能够访问父类变量,有什么办法可以在 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();
    }
}

我想访问有趣的 returnString(),就像我们在 java 中所做的那样,类一的静态函数,如果有人实现了这一点,请帮助。

标签: androidkotlin

解决方案


在您的情况下abcList是该类的成员变量。类的每个实例都有自己的成员变量版本,这意味着静态方法无法访问它们。如果您想从伴生对象访问它,它也必须是静态的。

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

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

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

此代码将起作用,但请记住,在这种情况下,只有一个abcList. 无法从静态函数访问成员变量(即使在 Java 中也不行)。

这是您的 Java 示例的 Kotlin 版本:

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()
    }
}

推荐阅读