Kotlin 静态方法和变量 [英] Kotlin static methods and variables

查看:31
本文介绍了Kotlin 静态方法和变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将一个类实例保存到一个公共静态变量中,但我不知道如何在 Kotlin 中做到这一点.

I want to be able to save a class instance to a public static variable but I can't figure out how to do this in Kotlin.

class Foo {

    public static Foo instance;
    public Foo() {
        instance = this;
    }

}

推荐答案

最接近 Java 静态字段的是伴随对象.您可以在此处找到它们的文档参考:https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects

The closest thing to Java's static fields is a companion object. You can find the documentation reference for them here: https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects

您在 Kotlin 中的代码如下所示:

Your code in Kotlin would look something like this:

class Foo {

    companion object {
        lateinit var instance: Foo
    }

    init {
        instance = this
    }

}

如果您希望将您的字段/方法作为静态公开给 Java 调用者,您可以应用 @JvmStatic 注释:

If you want your fields/methods to be exposed as static to Java callers, you can apply the @JvmStatic annotation:

class Foo {

    companion object {
        @JvmStatic lateinit var instance: Foo
    }

    init {
        instance = this
    }

}

这篇关于Kotlin 静态方法和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆