我怎么能创建一个子类型的`I`来包装其他子类型的`I`?

时间:2015-02-27 09:11:06

标签: scala generics scala-2.10 generic-programming

在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;
  }
}

我希望能够在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"

我想要的是data实例中的PassthroughReply应该与其包装子类型data的{​​{1}}具有相同的类型。

1 个答案:

答案 0 :(得分:2)

这个怎么样?

class PassthroughReply[T](val reply: Reply[T]) extends Reply[T] { 
    override def data = reply.data
}