https://kotlinlang.org logo
Title
b

bodiam

11/11/2018, 10:19 AM
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

elizarov

11/11/2018, 10:26 AM
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

bodiam

11/11/2018, 10:38 AM
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

igor.wojda

11/11/2018, 10:43 AM
Try
@file:JvmName("Network")
e

elizarov

11/11/2018, 10:46 AM
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

bodiam

11/11/2018, 10:47 AM
Sorry, forgot to say that I tried both.
e

elizarov

11/11/2018, 10:47 AM
(there are also related issues there)
b

bodiam

11/11/2018, 10:48 AM
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

elizarov

11/11/2018, 10:49 AM
If you are trying to keep binary API of your existing Java lib, then companion objects with
@JvmStatic
is what you do, indeed.
b

bodiam

11/11/2018, 10:52 AM
Thanks for the link to the issue. I'm not 100% sure if it's the same, but it's very similar.
@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

elizarov

11/11/2018, 10:53 AM
It is the issue. It will not compile when you have both
@file:JvmName("Network")
and
class Network(val name: String)
b

bodiam

11/11/2018, 10:56 AM
Thanks. I'll work my way around it, thanks (and no need to introduce statics into Kotlin, I think ;-)
1