Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Kotlin class object from Java

Tags:

java

kotlin

I have a Kotlin class which has a class object, e.g.

public class Foo {
    public class object {
        public val SomeValue : Int = 0
    }
}

If I'm using this class from Java, how do I access SomeValue inside the class object? If it were a Java class with a static property, I'd just use Foo.SomeValue - but I can't do that here.

IntellIJ shows that I can access Foo.object.$instance, but $instance doesn't have getSomeValue or anything like that. If I try to use $instance.SomeValue anyway, when I build the error message says:

SomeValue has private access in Foo.object

I'm using Kotlin 0.5.1.

like image 492
Wilka Avatar asked Feb 09 '13 14:02

Wilka


People also ask

Can I use Kotlin class in Java?

Kotlin code can be easily called from Java. For example, instances of a Kotlin class can be seamlessly created and operated in Java methods.

How do you call Kotlin class method from Java class?

One extremely useful feature in IntelliJ IDEA and Android Studio is the ability to see the compiled bytecode of your Kotlin code and then the decompiled Java code. For this, press Ctrl+Shift+A (Cmd+Shift+A on Mac) to invoke the action search, then type “Show Kotlin Bytecode” (or “skb”) and press Enter.

Can I use a Kotlin library in Java?

And yes you can! This works as listOf , like many of our daily Kotlin utility functions, are simply static functions you can use from Java.


2 Answers

As a workaround, you should be able to make the Kotlin field visible using @JvmField:

@JvmField var addressLocationBox: ToOne? = null
like image 66
Iman Marashi Avatar answered Nov 07 '22 08:11

Iman Marashi


The "absense" of getSomeValue() is a bug in the IDE. If you use it, it compiles OK. I created an issue: http://youtrack.jetbrains.com/issue/KT-3337

like image 26
Andrey Breslav Avatar answered Nov 07 '22 06:11

Andrey Breslav