I'm migrating part of application from Java to Kotlin and have a question about that.
What is preferable or better way ?
@file:JvmName("ClassX")
fun funX() {}
or
class ClassX {
companion object {
@JvmStatic
fun funX() {}
}
}
Let's look at the decompiled code to answer this question.
Kotlin file with a @JvmName
annotation like yours:
@file:JvmName("ClassX")
fun funX() {}
will be compiled into a bytecode, analogous to this Java code:
@JvmName(
name = "ClassX"
)
public final class ClassX {
public static final void funX() {
}
}
Pretty similar to what you'd probably write when using Java, right?
A Kotlin class with a companion object like this:
class ClassX {
companion object {
@JvmStatic
fun funX() {}
}
}
is analogous to this Java code:
public final class ClassX {
public static final ClassX.Companion Companion = new ClassX.Companion((DefaultConstructorMarker)null);
@JvmStatic
public static final void funX() {
Companion.funX();
}
public static final class Companion {
@JvmStatic
public final void funX() {
}
private Companion() {
}
// $FF: synthetic method
public Companion(DefaultConstructorMarker $constructor_marker) {
this();
}
}
}
As you see, class with a companion object will generate more code.
Is it good or bad? You decide. I'd say it's bad and it's better to use a file with @JvmName
annotation. There is also a discussion on Kotlin's forum about this topic: read the best practices.
BTW, you can look at the bytecode and decompiled Java code in IntelliJ IDEA via "Tools" -> "Kotlin" -> "Show Kotlin Bytecode".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With