3

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

feridok
  • 648
  • 7
  • 26
  • 1
    https://stackoverflow.com/questions/39303180/kotlin-how-can-i-create-a-static-inheritable-function – Ethan Choi Jul 30 '19 at 13:17
  • Possible duplicate of [Are static methods inherited in Java?](https://stackoverflow.com/questions/10291949/are-static-methods-inherited-in-java) – cutiko Jul 30 '19 at 13:18

2 Answers2

2

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()
jsvilling
  • 233
  • 2
  • 6
0

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
    }
}
Sandeep Tak
  • 41
  • 1
  • 3