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