chevron-up bell reply instagram twitter2 feed3 finder search-25px-p0

Why Kotlin doesn’t have static

2017-11-16

As you may observe while programming with Kotlin (1.1.60), there is no static members or methods. Instead you can use the companion object to work it around.

The reason behind this is: https://discuss.kotlinlang.org/t/what-is-the-advantage-of-companion-object-vs-static-keyword/4034

Scala also replaces class level declarations with a 'Singleton' object. The main advantage of this is that everything is an object. In Java, static members are treated very differently than object members. This means that you can't do things like implementing an interface or putting your class 'instance' into a map or pass it as a parameter to a method that takes Object. Companion objects allow for these things. That's the advantage.

If you want to use the above code as static members/methods in Kotlin, which is 100% fine. However, when I read more from its reference docs: https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#static-fields.

 

And found out, on the JVM you can have members of companion objects generated as real static methods and fields, if you use the @JvmStatic annotation. See the Java interoperability section for more details.

Simply put, if you want your java code to use Kotlin static member/methods, you might use of the following methods:

  • const
  • @JvmField
  • lazyInit

 

 

Reference

  • http://www.arkilis.me/
  • https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#static-fields
  • https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects

 

 

arkilis

Comments: