Home Why and when to use @JvmStatic with companion objects?
Reply: 0

Why and when to use @JvmStatic with companion objects?

user1262
1#
user1262 Published in June 19, 2018, 11:54 pm

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:

TestKotlin.kt

class TestKotlin {
    companion object {
        val someString = "hello world"
    }
}

Which is then called by Java, like this:

TestJava.java

public class TestJava {
    String kotlinStaticString = TestKotlin.Companion.getSomeString();
}

but then, there's this option 2:

TestKotlin.kt v2

class TestKotlin {
    companion object {
        @JvmStatic  // <-- notice the @JvmStatic annotation
        val someString = "hello world"
    }
}

And then, call it from Java, like this:

TestJava.java v2

public class TestJava {
    String kotlinStaticString = TestKotlin.getSomeString();
}

So my questions are:

  • Are these 2 cases any different, in terms of behavior or memory allocation?
  • Is there a preference on which one to use?
  • Do both create a pseudo static singleton object, like Java static does?

Thanks!

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.326507 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO