Android studio convert to Kotlin: Use @JvmStatic in some cases

613 Views Asked by At

I have been using Kotlin over Android for quite intensively. It does make programming fun again. Still, in some cases (mostly util classes where the name should be short and handy), when automatically converting Java to Kotlin, I would love to have an option to use @JvmStatic on static methods rather than converting callers to MyClass.Companion.Bar.

That is, in some specific cases, it would be nice to have

public static foo(Barian bar)

converted to

@JvmStatic
fun foo(bar:Barian)

so I can maintain the short calling syntax from Java:

MyClass.foo(bar)

rather than

MyClass.Companion.foo(bar)

Obviously, in most cases I agree it's bad manners for many reasons such as future compatibility, non-Kotlin spirit and many more, but in a few cases it can keep Java code (that uses my classes) shorter.

1

There are 1 best solutions below

1
On

You don't need to specify the Companion-namespace explicitly, when you decalre your "static" method like this:

class MyClass {

    companion object {
        fun foo() {}
    }
}

In this case you still can call it via:

MyClass.foo()

But nevertheless having static methods is not a Kotlin-idiomic way and should be avoided by using other features of this language.