0

Given the following in Java:

public interface Reply<T> {
  T data();
}

public class StatusReply implements Reply<String> {
  private final String status;

  public StatusReply(String status) {
    this.status = status;
  }

  @Override
  public String data() {
    return status;
  }
}

I want to be able to do this in Scala:

class PassthroughReply[R <: Reply[_]](val reply: R)
  extends Reply[T] { // won't compile, `T` type not found

    override
    def data[T : Reply]: T = reply.data
}

val statusReply = new StatusReply("OK")
val passthroughReply = new PassthroughReply[SatusReply](statusReply)
passthroughReply.data // Should return "OK"

What I want is that the data in an instance of PassthroughReply, should have the same type as the data of its wrapped sub type of Reply.

1 Answers1

2

How about this?

class PassthroughReply[T](val reply: Reply[T]) extends Reply[T] { 
    override def data = reply.data
}
Upio
  • 1,364
  • 1
  • 12
  • 27
  • If I do this, I would need to pass the type used by StatusReply e.g. `new PassthroughReply[String](new StatusReply("OK"))` I want it so that PassthroughReply can just infer the type used by StatusReply automatically. – Ramon Marco L. Navarro Feb 27 '15 at 10:02
  • 1
    The type of PassthroughReply can be inferred from the parameters you use to construct it. Try new PassthroughReply(new StatusReply("OK")) – Upio Feb 27 '15 at 10:10
  • I'm sorry, but I need to be able to type check with the type of `Reply`, e.g. `PassthroughReply[StatusReply]` instead of `PassthroughReply[String]`. – Ramon Marco L. Navarro Feb 27 '15 at 15:10