【发布时间】:2019-12-31 13:52:45
【问题描述】:
我正在尝试在其他类中调用一个类的静态函数,例如 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 中做的一类的静态函数,如果有人实现了这个,请帮助。
【问题讨论】:
-
你也不能在 java 中这样做,除非 abcList 也是静态的。尝试将 abcList 移动到伴随对象中
-
如何在 kotlin 类中将 abcList 设为静态,因为我在第一类中的其他函数也在使用 abcList 进行某些操作@TimCastelijns
-
静态函数无法访问非静态函数/变量,Kotlin 也是如此。
-
你为什么不扩展
one类