Daily Kotlin: Static methods

Aanand Shekhar Roy
AndroidPub
Published in
4 min readOct 19, 2017

--

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…

--

--

Aanand Shekhar Roy
AndroidPub

Senior Software Engineer @Joist, Author of Kotlin Programming Cookbook.