在 Kotlin 中声明静态属性?

问题描述 投票:0回答:3

我的

Java
代码:

public class Common {
    public static ModelPengguna currentModelPengguna;
}
java kotlin static-methods static-block
3个回答
14
投票
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


1
投票

Java 对许多功能使用相同的

static
关键字,例如:

  • 全局变量/属性。
  • 常数,如:
    private static final String TAG = ...
  • 类的加载初始化器 - Java 命名为 Static-block。

虽然 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
    不需要传递所有参数

注意

: MyType
”部分可以省略,因为 Kotlin 和 Android-studio IDE 都会根据初始化器自动检测类型(例如,基于“
 = MyType()
”部分)。

此外,

@JvmStatic
@JvmOverloads
不需要任何导入(因为它们是 Kotlin 的内置功能)。


0
投票

静态变量声明并初始化为伴随对象,例如:

 public class MyClass {

    companion object{
        const val TAG: String = "my-tag"
        const val myVariable: MyType = MyType()
        var myNullableVariable: MyType? = null
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.