我的
Java
代码:
public class Common {
public static ModelPengguna currentModelPengguna;
}
public class Common {
companion object {
val currentModelPengguna: ModelPengguna = ModelPengguna()
}
}
或者如果对象是静态的并且你希望它作为单例 你可以使用
object Common {
val currentModelPengguna: ModelPengguna = ModelPengguna()
}
a static property in kotlin 由
companion object
延伸阅读:
https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects
Java 对许多功能使用相同的
static
关键字,例如:
private static final String TAG = ...
虽然 Kotlin 将这些分开。
如果我们有一个 Java 文件,比如:
public class MyClass {
private static final String TAG = "my-tag";
@NonNull
public static MyType myVariable = new MyType();
@Nullable
public static MyType myNullableVariable = null;
static {
Log.d(TAG, "Got this far!");
}
public void onSomething() {
onSomething(false);
}
public void onSomething(optionalArg: Boolean) {
// ...
}
}
然后 Kotlin 版本可能看起来像:
open class MyClass {
companion object {
private const val TAG = "my-tag"
@JvmStatic
var myVariable: MyType = MyType()
@JvmStatic
var myNullableVariable: MyType? = null
init {
Log.d(TAG, "Got this far!")
}
}
@JvmOverloads
open fun onSomething(optionalArg: Boolean = false) {
// ...
}
}
地点:
Kotlin 的
open class
就像 Java 的public class
.
“
@JvmStatic
”部分允许Java使用Kotlin的myVariable
,就好像它是Java的static
成员一样。
“
@JvmOverloads
”部分允许Java调用Kotlin的onSomething
不需要传递所有参数
注意“
”部分可以省略,因为 Kotlin 和 Android-studio IDE 都会根据初始化器自动检测类型(例如,基于“: MyType
”部分)。= MyType()
此外,
和@JvmStatic
不需要任何导入(因为它们是 Kotlin 的内置功能)。@JvmOverloads
静态变量声明并初始化为伴随对象,例如:
public class MyClass {
companion object{
const val TAG: String = "my-tag"
const val myVariable: MyType = MyType()
var myNullableVariable: MyType? = null
}
}