Static Methods and variables in Kotlin

I presume most Java programmers write some helper static methods and most probably even have some helper class including just these. So sooner or later you will need to write static methods like this in Kotlin.

public static float getPxFromDp(Context context, float dp) {
        Resources r = context.getResources();
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
    }

But you will find out you there is not anything like a static method in Kotlin. Fortunately, there are ways around this.

Create package-level function
Insert function into kotlin file. Don’t create any class declaration. You can now call a function from other Kotlin classes inside the package.

package com.example.app.util

import android.content.Context
import android.util.TypedValue


fun getPxFromDp(context: Context, dp: Float): Float {
    val r = context.resources
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.displayMetrics)
}

You can also call a function from Java code. A compiler will create a class with class name and KT suffix and you can call this function as any other static method.

UtilsKt.getPxFromDp(context, 20);

Insert function into Companion Object

package com.example.app.util

import android.content.Context
import android.util.TypedValue


class Utils{
    
    companion object {
        
        @JvmStatic
        fun getPxFromDp(context: Context, dp: Float): Float {
            val r = context.resources
            return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.displayMetrics)
        }
    }
}

This way you can call function standard old java way.

Utils.getPxFromDp(context, 20f)

Please notice @JvmStatic annotation. This enables you to call code from Java same way. Without this annotation you can only access function throught Companion object.

Utils.Companion.getPxFromDp(mContext, 20);

This all applies to variables as well, so you can define your constants in Kotlin file outside class declaration or inside companion object. In first case compiler generates getter method with variable name and prefix get for use in Java (so it is not really beautiful in case of constants).

val TAG = "UTILS"

Can be then called from Java

UtilsKt.getTAG();
Share this...
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

One thought on “Static Methods and variables in Kotlin

Leave a Reply

Your email address will not be published. Required fields are marked *