[英]How to access static variable of java class in kotlin?
Eg: I have a java class First 例如:我有一个Java类First
First.java 第一.java
`class First{
public static TAG = "test"
}`
Second.kt 秒
`class Second{
First.TAG /*Error classifier First does not have a companion object,and thus must be initialized here*/
}`
So help me to call the static variable TAG declared in First.java inside Second.kt kotlin class 因此,请帮助我调用Second.kt kotlin类中在First.java中声明的静态变量TAG
Java Class: Java类:
class First {
public static String TAG = "test";
}
Kotlin Class: Kotlin类别:
class Second {
val secondTag: String = First.TAG
}
and there is no problem. 没问题
Try with IntelliJ IDEA 尝试使用IntelliJ IDEA
fun main(args: Array < String > ) {
val s = Second()
println(s.secondTag)
}
prints test
打印
test
Just make a proper, static final constant. 只需设置一个适当的静态最终常量即可。
class First {
public static final String TAG = "test"
}
Now you can call it from Kotlin. 现在您可以从Kotlin调用它。
class Second {
fun blah() {
val tag = First.TAG
}
}
First Class 头等舱
package com.your.package object First { val TAG: String= "Your TAG"; }
Second Class 二等
class Second{ First.TAG }
Kotlin doesn't have static members or member functions, you can use companion object Kotlin没有静态成员或成员函数,可以使用伴随对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.