Maybe a stupid question, but I've got quite a few ...
# getting-started
b
Maybe a stupid question, but I've got quite a few companion objects, which need to be accessed from Java. Is there somehow a way to make all the functions is the companion objects JvmStatic by default, or, at least, put an annotation on the companion object or something? It would save me a ton of annotations.
👍 2
e
There is no easy way to do it, but you can consider using top-level functions and top-level variables instead of companion objects. They looks nicer in Kotlin code and, at the same time, are automatically available as static methods from Java.
b
Thanks Roman. Appreciate it, but now I would like to rename the classname too. If I don't add anything, my classname is called NetworkKt.myStaticMethod(). But I'd like to call Network.myStatic(). I've tried adding @file:JvmName("Network") add the top of the file. but then IntelliJ can't find the class anymore. Any idea?
(I also have a class with the same name there, class Network). I've tried adding @file:JvmMultifileClass, but no luck
i
Try
@file:JvmName("Network")
e
You cannot have them in the same class if you have a class with the same name. I personally prefer
StuffKt
convention, but some people use
@file:JvmName
to rename it to
StuffUtil
or
Stuffs
.
b
Sorry, forgot to say that I tried both.
e
(there are also related issues there)
b
Right. The thing is, I'm trying to convert a Java lib to Kotlin, and I'd like to keep the number of changes to a minimum. If I start introducing new classes, that's not great. I'll stick to the @JvmStatic for now, that solves the issue.
e
If you are trying to keep binary API of your existing Java lib, then companion objects with
@JvmStatic
is what you do, indeed.
b
Thanks for the link to the issue. I'm not 100% sure if it's the same, but it's very similar.
Copy code
@file:JvmName("Network")

class Network(val name: String)

fun use(val name: String) {

}

Network.use(“test”) // doesn’t work
the last line doesn't work from Java. If I put that code in a companion object, and annotate it with JvmStatic, it works fine.
e
It is the issue. It will not compile when you have both
@file:JvmName("Network")
and
class Network(val name: String)
b
Thanks. I'll work my way around it, thanks (and no need to introduce statics into Kotlin, I think ;-)
âž• 1