【问题标题】:How could I create a sub type of `I` that would wrap other sub types of `I`?我怎样才能创建一个“I”的子类型来包装“I”的其他子类型?
【发布时间】:2023-03-14 11:24:01
【问题描述】:

在 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"

我想要的是PassthroughReply 实例中的data 应该与Reply 的包装子类型的data 具有相同的类型。

【问题讨论】:

    标签: scala generics scala-2.10 generic-programming


    【解决方案1】:

    这个怎么样?

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

    【讨论】:

    • 如果我这样做,我需要传递 StatusReply 使用的类型,例如new PassthroughReply[String](new StatusReply("OK")) 我想要它,以便 PassthroughReply 可以自动推断 StatusReply 使用的类型。
    • PassthroughReply 的类型可以从你用来构造它的参数中推断出来。尝试新的 PassthroughReply(new StatusReply("OK"))
    • 很抱歉,我需要能够使用 Reply 的类型进行类型检查,例如PassthroughReply[StatusReply] 而不是 PassthroughReply[String]
    猜你喜欢
    • 2023-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 2011-09-22
    • 2023-01-05
    相关资源
    最近更新 更多