How to access Kotlin companion objects from Java
Asked Answered
I

1

6

I have this Kotlin class:

class Storage {
    companion object {
        val COL_ID = "id"
    }
}

and I want to use the COL_ID in my Java code:

doSomething(Storage.COL_ID);

but, the compiler tells me that COL_ID is private. I have tried to add public to all the elements (class, object and val), but it has no effect.

How can I access these companion object constants?

Update I think my question is different from the given duplicate, because I want to create constants, instead of a static method.

Io answered 23/3, 2019 at 17:16 Comment(9)
You are missing const from your const val COL_ID (or @JvmField)Aldershot
@Aldershot that simple ...Io
Possible duplicate of How to access Kotlin companion object in Java?Schecter
@Steve no, it finds it, it just was not accesible.Io
Hmmm...I wouldn't think that would work. Ok, well, I don't understand it then. So what was the solution you ultimately came up with? You said you already tried making it 'public'Schecter
I'm new to Kotlin, so I'd really like to understand your soluton. All I can make work in my own IDE is: Storage.Companion.getCOL_ID() unless I add the @JvmStatic annotationSchecter
@Steve see my updated question and answer.Io
@BartFriederichs - cool. I'm still at a loss for what's going on here, as I don't see why making this 'const' would change how it is referenced. Do you have any insight into that? - +1'd your answer btw.Schecter
@Steve See discuss.kotlinlang.org/t/why-does-kotlin-need-const-keyword/….Tsarism
I
5

I added const, and everything was fine:

class Storage {
    companion object {
        const val COL_ID = "id"
    }
}
Io answered 23/3, 2019 at 18:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.