Search code examples
javagenericskotlinthriftsimplify

Thrift types as a Generic


I'm using Apache thrift which generates Java classes that look like this:

public class MyEvent implements org.apache.thrift.TBase<MyEvent, MyEvent._Fields>

I'd like to create a container class that takes a generic that implements TBase. I'd like to write code that looks like this:

(kotlin)

val msg = MyContainer<MyEvent>()

However, I can't do class MyContainer<T: TBase> as I need to fill in the two arguments for TBase, I did something like this:

class MyContainer<T: TBase<T,F>, F: TFieldIdEnum>

However this requires me to write code like this:

val msg = MyContainer<MyEvent, MyEvent._Fields>()

which I suppose works and otherwise gets me the functionality I need, but is there anyway I can more succinctly tell java "I need a T that implements TBase with type T and T._Fields" so I can do val msg = MyContainer<MyEvent>() ?


Solution

  • If it's only a container, you can use star-projection:

    class MyContainer<T: TBase<T,*>>
    

    That will make val msg = MyContainer<MyEvent>() work. This technique is sometimes useful when you work with objects using reflection anyway, as is the case with Protobuf and Thrift.

    But your question doesn't give hints as to how you plan to use this container.