Create a concrete Java class that uses recursive generics in Kotlin

Is it possible to create a specific Java class that uses recursive generics in Kotlin, if so, how?

More details

I am trying to create an instance of a Java class that uses recursive generics similar to the example below. I found work to package a Java class in a new class, but it looks like I'm facing a problem that I could work directly with.

Java class with recursive generics

public class MyLegacyClass<T extends MyLegacyClass<T>> {
    // implementation ...
}

How it is created in Java

// In Java we just ignore the generic type...
MyLegacyClass myLegacyClass = new MyLegacyClass();

Failed to create attempt in Kotlin

class myClass {
    // Error: One type argument expected for class...
    val x: MyLegacyClass = MyLegacyClass()

    // Still 'Error: One type argument expected for class..' You start to see the problem here. 
    val y: MyLegacyClass<MyLegacyClass<MyLegacyClass<MyLegacyClass>>> = MyLegacyClass()
}

Kotlin workaround

class MyLegacyClassWrapper : MyLegacyClass<MyLegacyClassWrapper>()

class myClass {
    val x: MyLegacyClass<MyLegacyClassWrapper> = MyLegacyClassWrapper()
}
+4
source share
1 answer

Is it possible to instantiate a specific Java class that uses recursive generics in Kotlin? if so, how?

, . .

Java:

public class MyLegacyClass<T extends MyLegacyClass<T>> {}

:

class MyLegacyClass<T : MyLegacyClass<T>>

T. , :

class MyLegacyClass<out T : MyLegacyClass<T>>

, Kotlin - Java.

MyLegacyClass T, , .

+4

Source: https://habr.com/ru/post/1687520/


All Articles