Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin static methods and variables

Tags:

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;     }  } 
like image 807
Caleb Bassham Avatar asked May 08 '17 21:05

Caleb Bassham


People also ask

Does Kotlin have static variables?

Kotlin doesn't support static keyword. It means that you can't create a static method and static variable in Kotlin class.

How do you initialize a static variable in Kotlin?

All we have to do is declare an init block inside the companion object of a class. This way, we get the same behavior as Java's static block. Put simply, when the JVM is going to initialize the enclosing class, it will execute the init block inside the companion object.

Can we create static methods in Kotlin?

Kotlin is a statically typed programming language for the JVM, Android and the browser, 100% interoperable with Java. Blog of JetBrains team discussing static constants in Kotlin.

How would a static method be written in Kotlin?

In Kotlin, we can achieve the functionality of a static method by using a companion identifier. For example, If you want to create a method that will return the address of your company then it is good to make this method static because for every object you create, the address is going to be the same.


2 Answers

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     }  } 
like image 150
Eduard B. Avatar answered Sep 24 '22 13:09

Eduard B.


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.

like image 33
Roman Elizarov Avatar answered Sep 24 '22 13:09

Roman Elizarov