Why and when to use @JvmStatic with companion objects?

前端 未结 3 1978
栀梦
栀梦 2020-12-23 09:30

I\'m trying to understand the difference between using/not using @JvmStatic, and when I should use either one.

So, with Kotlin and Java, I can do this:

3条回答
  •  失恋的感觉
    2020-12-23 10:01

    You place the function in the "companion object".

    So the java code like this:

    class DemoClass {
      public static int myMethod() { return 1; }
    }
    

    will become

    class DemoClass {
      companion object {
         fun myMethod() : Int = 1
      }
    }
    

    You can then use it from inside Kotlin code as

    DemoClass.myMethod();
    

    But from within Java code, you would need to call it as

    DemoClass.Companion.myMethod();
    

    (Which also works from within Kotlin.)

    If you don't like having to specify the Companion bit you can either add a @JvmStatic annotation or name your companion class.

    From the docs:

    Companion Objects

    An object declaration inside a class can be marked with the companion keyword:

    class MyClass {
       companion object Factory {
           fun create(): MyClass = MyClass()
       }
    }
    

    Members of the companion object can be called by using simply the class name as the qualifier:

    val instance = MyClass.create()
    

    ...

    However, on the JVM you can have members of companion objects generated as real static methods and fields, if you use the @JvmStatic annotation. See the Java interoperability section for more details.

    Adding the @JvmStatic annotation looks like this

    class DemoClass {
      companion object {
        @JvmStatic
        fun myMethod() : Int = 1;
      }
    }
    

    and then a will exist as a real Java static function, accessible from both Java and kotlin as DemoClass.myMethod().

    If it is just disliked by the Companion name, then you can also provide an explicit name for the companion object looks like this:

    class DemoClass {
      companion object Blah {
        fun myMethod() : Int = 1;
      }
    }
    

    which will let you call it from Kotlin in the same way, but from java like DemoClass.Blah.myMethod() (which will also work in Kotlin).

提交回复
热议问题