kotlingenericsinterface

Using Kotlin Generics in Nested Interfaces


I'm trying to write an interface for sending generic events to a remote server, along with a listener which returns a response that includes the list of events that was sent/attempted to be sent.

interface Sender<T> {
  interface Response {
    val success: Boolean
    val events: List<T> // unresolved reference
  }

  ...
}

If I change the T to a *, it compiles, but the type doesn't match what I need in the listener.

How can I "inherit" the generic type T in a sub-interface like this?


Solution

  • You can't. The only thing you can make work is

    interface Sender<T> {
      interface Response<T> {
        val success: Boolean
        val events: List<T> // unresolved reference
      }
    
      ...
      fun send(response: Response<T>) // or
      fun send(): Response<T>
    }
    

    You can't get around repeating the <T>, not with an interface, because you must be able to refer to Sender.Response even when you are not in a Sender object, or you have several Sender objects with different Ts, or whatever.