我试图在其他类中调用一个类的静态函数,例如 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()
}
}
Run Code Online (Sandbox Code Playgroud)
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()
}
}
Run Code Online (Sandbox Code Playgroud)
我想像我们在 java 中所做的那样,像第一类的静态函数一样访问有趣的 returnString(),如果有人已经实现了这一点,请帮忙。
psh*_*ger 10
在你的例子中abcList是类的成员变量。类的每个实例都有自己的成员变量版本,这意味着静态方法无法访问它们。如果您想从伴生对象访问它,它也必须是静态的。
class One {
companion object {
val abcList = ArrayList<String>()
fun returnString() {
println(abcList[0])
}
}
}
class Two {
fun tryPrint() {
One.returnString()
}
}
Run Code Online (Sandbox Code Playgroud)
这段代码可以工作,但请记住,在这种情况下,只有一个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()
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9199 次 |
| 最近记录: |