1

How to convert Java generics into kotlin language generics

The java code:

public abstract class Request<T, R extends Request> implements Serializable {}

But the kotlin code:How to do???

gooboot
  • 51
  • 3

3 Answers3

2

According to my needs, I finally realized this way.

Open abstract class Request < T, out R > (url: String): Serializable where R: Request < T, R > {}
Open class GetRequest < T > (url: String): Request < T, GetRequest < T > (url){

}

gooboot
  • 51
  • 3
0

You can just use the Java-to-Kotlin converter and get

abstract class <T, R : Request<*, *>> : Serializable

But the second Request (the one in extends Request) is a raw type which shouldn't be used in Java and is happily unsupported in Kotlin. Very likely it should be Request<T, R> instead; then the translation uses Request<T, R> in Kotlin too.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • "This type parameter violates Finite Bound Restriction." – Cililing Sep 30 '19 at 07:03
  • That's the error compiler throws when you try use two wildcards. Actually, I am not convenient that there should be `Request` - I see some use cases where second type parameter should be in `Request` bounds. – Cililing Sep 30 '19 at 07:26
  • Thank you very much for your help. According to my needs, I finally achieved this. Open abstract class Request < T, out R > (url: String): Serializable where R: Request < T, R > {} Open class GetRequest < T > (url: String): Request < T, GetRequest < T > (url){ } – gooboot Sep 30 '19 at 07:54
0

public abstract class Request<T, R extends Request> implements Serializable {}

So, we have two generic types. T, which can by any type and R which have to extends Request. But, Request still requires two parameters.

In Java it's simpler as generics are not so strict and we can use raw type.

In Kotlin it would be like this: abstract class Request<T, R : Request<*, *> : Serializable, but then we have a error: This type parameter violates Finite Bound Restriction. So, we need to specify somehow second type argument.

I am not sure if it is a correct way for your case, but you can do following:

abstract class Request<T, R : Request<*, R>> : Serializable {
    abstract val dummy: R
}

class ExampleRequest<T, N> : Request<T, ExampleRequest<T, N>>() {
    override val dummy: ExampleRequest<T, N> get() = this
}
Cililing
  • 4,303
  • 1
  • 17
  • 35
  • Thank you very much for your help. I learned some new knowledge from your help. According to my needs, I finally realized this way. Open abstract class Request < T, out R > (url: String): Serializable where R: Request < T, R > {} Open class GetRequest < T > (url: String): Request < T, GetRequest < T > (url){ } – gooboot Sep 30 '19 at 07:55