Member-only story
Daily Kotlin: Static methods
If you come from Java world, you are already familiar of static methods. They prevent us from copying our methods to every class and allows using them without creating an object. But, what if I told you that we don’t have static methods in Kotlin?!

True. But that doesn’t mean that we can’t reap the benefits p\rovided by static methods in Kotlin. There is a way around them. Let’s see how.
The documentation of Kotlin recommends that you should use package-level functions if you want to follow DRY. This might seem a little odd if you have worked with Java because it’s not there in Java! Let’s create a package level function in Kotlin. All you need to do is create a file with .kt extension and put a method which you’ll be using at multiple places. I’ll be creating a file name SampleClass.kt The content of SampleClass.kt is:
package packageA
fun bar(){
println("Method bar")
}
As you can see, we didn’t have to put our bar() method under some top-level class declaration. If you look at the decompiled code, it looks like the below:
public final class SameClassKt {
public static final void bar() {
String var0 = "Method bar";
System.out.println(var0);
}
}
Even though we didn’t put it under any class declaration, Kotlin, on compilation, will create a class with name SampleClassKt and will place the method inside it. And notice what the signature of our method is: public static final void bar() Exactly what we wanted to have!
If you want to call this function from any other class, let’s say HelloWorld.kt, you can call it by doing:
package packageB
import packageA.bar
fun main(args: Array<String>) {
bar()
}
Notice that we have to import that method from its package, hence the import packageA.bar statement.
Another way to do this, is by putting the method in object declaration.
package packageA
object Foo{
fun bar() = println("Method bar")
var foo="foo"
}
And you can access it like:
Foo.bar()
The object declaration is mostly used inside a class, it is useful if you want to access the internals of the class. To understand it…