22

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.

Wilka
  • 28,701
  • 14
  • 75
  • 97
  • You could also make it `@JvmStatic` allowing it to be accessed as a static member of the class `Foo`. See full docs on interoperability from Java to Kotlin https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#static-methods-and-fields – Jayson Minard Dec 29 '15 at 14:30

4 Answers4

30

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

@JvmField var addressLocationBox: ToOne? = null
Iman Marashi
  • 5,593
  • 38
  • 51
7

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

Andrey Breslav
  • 24,795
  • 10
  • 66
  • 61
7
data class YourClass(@JvmField val name: String)
Yoco
  • 71
  • 1
  • 1
  • 9
    Welcome to SO. Please add some explanation to your answer. – m02ph3u5 Apr 07 '20 at 11:25
  • As an explanation of why this works, if you are using a data class in Kotlin you need to add `@JvmField` in front of the variable definitions in the data class constructor if you want the variables to be accessible from Java. – Soren Stoutner Jul 29 '21 at 02:00
  • My problem was the class defined in Kotlin was not recognized in the java code. When I added @JvmField to one of the params, it suddenly knew about the class defined in the .kt file – Markus Jul 26 '22 at 12:54
0

To set a custom name for the generated Java class, use the @JvmName annotation:

Kotlin

@file:JvmName("DemoUtils")

package com.example

class Util

fun getTime() { /*...*/ }

Java

new com.example.Util();
com.example.DemoUtils.getTime();

Moreover, if you use the @JvmMultifileClass, then:

@file:JvmName("Utils")
@file:JvmMultifileClass

package com.example

fun getDate() { /*...*/ }

Java

com.example.Utils.getDate();
Mori
  • 2,653
  • 18
  • 24