Blog

What is Static in Kotlin?

By 28 October 2020 January 7th, 2021 No Comments

What is Static in Kotlin?

Benefits of static in kotlin

Sharing is caring!

If you have already worked with Java, you must know that static provides a way to share a single copy of method and variables among all classes using class name without creating its object but if I say- There is no static available in Kotlin. Don’t panic! Yes, but there is nothing to worry about. There is other way around which we can get the benefits of static in Kotlin. Let’s have a look at it one by one:

1. Declaring package-level functions:

Just create a file with .kt and put the desired methods and properties in it without declaring a class.

fun printMessage(message : String){ println(“Message : $message) }

Here I have created a file named Utils.kt and declared a method that simply gives below message. On compilation, all the methods given in Utils.kt will convert into a static method of Java class named UtilsKt. Java equivalent code on decompiling looked like this:

public final class UtilsKt { public static final void printMessage(@NotNull String message) { Intrinsics.checkParameterIsNotNull(message, “message”); String var1 = “Message : ” + message; boolean var2 = false; System.out.println(var1); } } In Kotlin you can call this method like this: fun main(args:Array<String>){ printMessage(“Hello World”) }

2. Using Companion object:

Using companion object we can achieve the functionality of static very easily in Kotlin. Whatever method that we want to work as static we need to define it inside the companion block. Let’s see how we can do the above example using companion object:

class Utils { companion object { fun printMessage(message: String) { println(“Message : $message) } } }

Now we can access this printMessage method using class name like this: fun main(args : Array<String>){ Utils.printMessage(“Hello World”) } In java we can access this method like this:

Utils.Companion.printMessage(“Hello world”);

If you don’t want to use companion word while calling you can also provide it a name:

companion object printMsg{ fun printMessage(message: String) { println(“Message : $message) } }

And access it like:

Utils.printMsg.printMessage(“Hello world”);

Or you can use @JvmStatic annotation to omit this companion and any name to access method in Java.

companion object printMsg{ @JvmStatic fun printMessage(message: String) { println(“Message : $message) } }

Now you can call it just by class name Utils.printMessage(“Hello world”);

In Kotlin, you can still call the method just by the class name only i.e.

Utils.printMessage(“Hello world”).

Get started with Bloom