Kotlin static methods and variables

后端 未结 4 1269
南方客
南方客 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 05:51

    You can create a companion object for the class, and if you want the field to be static you can use the annotation @JvmStatic. Companion object have access to private members of the class it is companion for.

    See below an example:

    class User {
        private lateinit var name: String
    
        override fun toString() = name
    
        companion object {
            @JvmStatic
            val instance by lazy {
                User().apply { name = "jtonic" }
            }
        }
    }
    
    class CompanionTest {
    
        @Test
        fun `test companion object`() {
            User.instance.toString() shouldBe "jtonic"
        }
    }
    

提交回复
热议问题