Kotlin static methods and variables

后端 未结 4 1272
南方客
南方客 2020-11-30 05:15

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 i         


        
4条回答
  •  Happy的楠姐
    2020-11-30 06:00

    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

    Your code in Kotlin would look something like this:

    class Foo {
    
        companion object {
            lateinit var instance: Foo
        }
    
        init {
            instance = this
        }
    
    }
    

    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
        }
    
    }
    

提交回复
热议问题