Is `@JvmStatic` ever actually needed other than fo...
# getting-started
j
Is
@JvmStatic
ever actually needed other than for a main method? I'm writing some kotlin code which will be used by Java code (which I don't have access to, so I don't know exactly how my functions will be used). Is it better to just mark something with the annotation if I know it's expected to be static in the Java code?
l
You need it when something is using Java reflection to call the method.
Also if you have Kotlin code where you want to expose an API for Java code to call, and you want that API to have a simple static method.
But yeah, I looked at my personal project (not very big, around 80k lines of code) and I only use it for main methods, a few test cases where some reflection is used, and in the entry point for a JavaFX module.
👍 1
s
another example of where you need it is when writing Tests with DataProviders using TestNG (obviously) in Kotlin, because those are supposed to be static methods. But when you Kotlin lib is supposed to be called from Java it's mostly for ergonomic purposes, I presume.
d
Is it needed for main methods? I’ve never used it for that.
j
@Daniel Pitts I typically will put my main method of my gui application inside the companion object of the main window class. I believe you need to mark the function with JvmStatic for this usage.
l
You need it if you use JavaFX and want to use their special way of starting applications, right? Beciase if I'm not mistaken, it looks at the stack trace to determine the name of the class it was started from.
d
Ah, I’ve only used top level main methods in Kotlin, and haven’t used JavaFX, only Swing/awt.
l
Well, the JavaFX trick is quite ugly. It's expected that the main method is in the
Application
instance, so you call the
launch
method directly from the
main
method, the
launch
then looks at the stack trace to determine the class which the main method lives in, and instantiates it.
You can imagine the number of ways this could fail to do what you expect.
d
I never did like “magic” code.
s
every sufficiently advanced code is indistinguishable from magic 🤷‍♂️ But yes, I feel lost in a Spring app as well that "should work" but for some non-obvious reason doesn't.
d
Even when I understand how something works, if it doesn’t give me the ability to adjust the workings, I call it “black magic”. It’s fine to make the simple tasks easy, just don’t make the medium tasks impossible.
l
Agreed. And Spring was a great example of this as well.
plus1 1
Gradle may be one of the worst offenders, but other build systems are similar. You're not expected to understand how it actually works, and in many cases most developers wouldn't be able to manually build anything with said tool.
plus1 1