JJS
JJS

Reputation: 266

Java Generic getting type parameter

In Scala, you can define a class as this:

class MyClass[T1[T2]] {
  def abc(a1: T1[Double]):T1[Int] = ???
}

In this code, type parameter T1 represents a type that needs one type parameter T2, so we can create an instance like new MyClass[List].

I want to do this in Java, but I don't have any idea.

I wonder if it is possible in Java, and if not, any idea how I can do this thing in Java.

From my understanding, generic type essentially makes a function of types. So if you have a class like List<T>, you can think of the class List a function of type, so List takes a type parameter like Integer, then it will be a concrete type like list of integers(List<Integer>).

MyClass above takes a type parameter T1, but I want this T1 is also a generic type that takes a type parameter T2, so I can create an instance like MyClass<List> and can use type like List<Integer> or List<Double> inside MyClass. In Scala, if you try MyClass[Int] or MyClass[String] will fail because Int or String does not take a type parameter.

Of course, this may not be necessary if I allow to duplicate some codes, but to make a more general code, I think it is indispensable.

Upvotes: 3

Views: 320

Answers (1)

SpaceTrucker
SpaceTrucker

Reputation: 13556

The only way for this to work in Java is to have a common interface for T1.

public interface GenericType<T> {
    // ...
}

Then you can define your class as:

class MyClass {
    public GenericType<Integer> abc(GenericType<Double> a1) {
        //...
    }
}

Note that you don't need any more type parameters at the class level anymore because of the common interface. Then before invoking MyClass.abc you would need to wrap the instance you are passing in GenericType.

You can also go one abstraction level higher and define

class MyClass<T1,T2> {
    public GenericType<T1> abc(GenericType<T2> a1) {
        //...
    }
}

This would give you some more flexibility in using MyClass. But that is heavily dependent upon how MyClass is actually implemented.

Upvotes: 1

Related Questions