Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static function not visible in kotlin when extended from java

I'm writing Kotlin alongside java in an Android project, I have an abstract Java BaseApplication class which has some static methods, and my Application classes for each flavors extends this BaseApplication class (called App.kt) and are written in Kotlin. I wonder why I cant access BaseApplication static functions through App class in Kotlin code


public abstract class BaseApplication extends Application {
    public static void staticFunction(){
        Log.d("TAG", "some log...");
    }
}
public class App : BaseApplication() {
    fun doSomething(){
        Log.w("TAG", "doing something")
    }

I can call App.staticFunction() from a Java class but I cant call it from a Kotlin class. Am I doing something wrong? Why I can't call App.staticFunction() ? What is the difference?

I can do this from java:

public class JavaTest {
    public void main(String[] args) {
        App.staticFunction();
    }
}

But this(kotlin) gives me compile error:

class KotlinTest {
    fun main(args: Array<String>) {
        App.staticFunction()  //unresolved reference: static function
    }
}

(I know I can access staticFunction through AbstractApplication, I just want to know why I cant access it through App class?)

like image 335
feridok Avatar asked Sep 18 '26 05:09

feridok


1 Answers

From the Kotlin documentation on Java interop:

Static members of Java classes form "companion objects" for these classes. We cannot pass such a "companion object" around as a value, but can access the members explicitly ...

Your App class is a Kotlin class and doesn't know anything about the static method. However there should be a companion object that has been created for the static Method on the BaseApplication Java class. So you should be able to call the static method with

BaseApplication.staticFunction()
like image 57
jsvilling Avatar answered Sep 20 '26 20:09

jsvilling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!