Scala does not see Kotlin companion object functions

We published a Kotlin based library, and the Java crowd has no issues using it. However, we now have a Scala team trying to use it, and for whatever reason Scala cannot see anything in the Kotlin companion object:

class KotlinClass {
  companion object {
    fun someFun()...
  }
}

Scala code:

  KotlinClass.Companion.<someFun doesn't show up as an option here!!!>

What gives?

I don’t reall know scala but my guess is that you need to get the instance of the companion object.

KotlinClass.Companion.INSTANCE.someFun() 

Alternatively you could try to annotate the functions in your companion object with @JvmStatic.

Doesn’t this defeat the purpose of companion objects being singletons?

Sry, it’s been a while since I used kotlin from java. Your right and my example is wrong. There should be some sort of static INSTANCE field which contains the singleton instance.

I guess INSTANCE$ refers to Scala’s companion object, not Kotlin’s. Kotlin’s shows up in Java as Companion .

Answering my own question with a workaround, everything works if we wrap the companion in a Java class as such:

CompanionProxy.java

public class CompanionProxy {
    public final static KotlinClass.Companion companion = KotlinClass.Companion;
}

Then from Scala:

  CompanionProxy.companion.someFun()

Not sure why direct access to the Companion object from the Kotlin class doesn’t work…

Probably it’s this problem: https://youtrack.jetbrains.com/issue/KT-29864.

You can workaround it by giving the companion object an explicit name: companion object Something { ... }

1 Like

Yes, that’s it. Unfortunately we have published the library already, and there are people referring to Companion, so we can’t change it.

We gave the pesky Scala guys a Java class with the workaround above - along with our recommendation to migrate to a better language :wink: