android - 在 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 中所做的那样,类一的静态函数,如果有人实现了这一点,请帮助。
解决方案
在您的情况下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()
}
}
推荐阅读
- python-poetry - 为什么诗歌只能从 .poetry\bin 目录中获得?
- google-chrome - Chrome 无法在 Mac 上启动本机消息传递主机
- python - 你能检查一个变量是否等于字典中的任何值吗
- php - PHP SQL 服务器查询
- latex - 乳胶桌太宽
- javascript - 在 fetch api 中使用 FormData() 不起作用
- swift - 如何根据内容自动调整 NSTextView 的大小?
- arrays - 使用 ArrayFormula() 进行小计
- c# - ExRam Gremlinq 无法与 Cosmos DB 一起使用
- python - beaglebone black:启用 uart 时没有插槽