1

I’m struggling with value classes in generics and interoperability with Java or Groovy. Value class are inlined: Inline classes | Kotlin 1 except for generics.

Given following value class and interface (Kotlin):

@JvmInline
value class ValueClass(val id: String)

interface ValueClassListProvider {
    @Suppress("INAPPLICABLE_JVM_NAME")
    @JvmName("values")
    fun values(): List<ValueClass>

    @Suppress("INAPPLICABLE_JVM_NAME")
    @JvmName("value")
    fun value(): ValueClass
}

how can I implement ValueClassListProvider interface in Java or Groovy?

class ValueClassListProviderImplJava implements ValueClassListProvider {
    public List<ValueClass> values() {
        return Arrays.asList(new ValueClass("1"));
    }

    public String value() {
        return "1";
    }
}

Trying to run following code:

public static void main(String[] args) {
    ValueClassListProviderImplJava provider = new ValueClassListProviderImplJava();
    System.out.println(provider.values());
}

result in:

java: cannot find symbol
  symbol:   constructor ValueClass(java.lang.String)
  location: class pl.test.valueclass.ValueClass

For Groovy implementation of ValueClassListProvider interface:

class ValueClassListProviderImplGroovy implements ValueClassListProvider {

    List<String> values() {
        return ["1", "2"]
    }

    String value() {
        return "1"
    }
}

it compiles and seems to work, but when this implementation is later used in Kotlin code (suppose this is stub used in spock tests), it blows with:

java.lang.ClassCastException: class java.lang.String cannot be cast to class pl.test.valueclass.ValueClass

Is it possible to create instance of value class in Java or Groovy (needed for generics)?

  • By inspecting the class file, that constructor you want to call appears to be private. There is, however, a public method called `box-impl` that you can call with reflection to get a `ValueClass` object from `String`. Though I don't think that is a good solution at all... – Sweeper Oct 22 '21 at 09:10
  • I think that it's not supported yet, here you can find more information about it https://github.com/Kotlin/KEEP/blob/master/notes/value-classes.md#arrays-of-inline-value-classes – szymon_prz Oct 22 '21 at 10:22

0 Answers0