Kotlin static methods and variables

后端 未结 4 1270
南方客
南方客 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条回答
  •  眼角桃花
    2020-11-30 06:03

    It looks that you want to define a singleton object. It is supported in Kotlin as a first-class concept:

    object Foo {
      ... 
    }
    

    All the boilerplate code with static field and constructor is taken care by the Kotlin automatically. You don't have to write any of that.

    From the Kotlin code you can refer to the instance of this object simply as Foo. From the Java code you can referer to the instance of this object as Foo.INSTANCE, because the Kotlin compiler automatically creates the corresponding static field named INSTANCE.

提交回复
热议问题