feridok
feridok

Reputation: 658

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?)

Upvotes: 3

Views: 1408

Answers (2)

jsvilling
jsvilling

Reputation: 333

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()

Upvotes: 2

Sandeep Tak
Sandeep Tak

Reputation: 71

you can use easily

public class App : BaseApplication() {
    fun doSomething(){
        Log.w("TAG", "doing something")
        BaseApplication.staticFunction()
    }

   override fun onCreate() {
       super.onCreate()
       staticFunction() // you can call without problem
    }
}

Upvotes: 0

Related Questions