简体   繁体   English

上型绑定相对于子类型化的优势

[英]Advantage of Upper Type Bound over Subtyping

What is the advantage of using upper type bounds over just type in this example? 在此示例中,使用上限类型而不是仅类型有什么好处?

Why people prefer this 为什么人们喜欢这个

trait Pages[T <: Page] {
  val pages: Seq[T]
  def find(id: String): Option[T] = pages.find(_.id == id)
  def all: Seq[T] = pages
}

Over this: 在此:

trait Pages {
  val pages: Seq[Page]
  def find(id: String): Option[Page] = pages.find(_.id == id)
  def all: Seq[Page] = pages
}

It's the same as the advantage of your second example over 这与第二个示例相比的优势相同

trait Pages {
  val pages: Seq[Any]
  def find(id: String): Option[Any] = pages.find(_.id == id)
  def all: Seq[Any] = pages
}

: more precise types, allowing you not to mix up different subtypes of Page , to access operations of MyPage without casting, etc. :更精确的类型,允许您不要混合使用Page不同子类型,而无需进行铸造等即可访问MyPage操作。

Also, if you have the first and need the second, you can just use Pages[Page] ; 另外,如果您有第一个而又需要第二个,则只需使用Pages[Page] if you have the second and need the first, you are out of luck. 如果您拥有第二个并且需要第一个,那么您就不走运了。

Ok, I found out that in the first case I can specify type explicitly. 好的,我发现在第一种情况下,我可以显式指定类型。 If MyPage is subtype if Page . 如果MyPagePage子类型。

val pages = new Pages[MyPage]{
  override val pages: Seq[MyPage] = List(MyPage("a"), MyPage("b"))
}

And the compiler can infer the type so that pages.find("a") will be the MyPage type. 并且编译器可以推断类型,以便pages.find("a")将成为MyPage类型。 In the second example the type always will be Page , which forces to cast it. 在第二个示例中,类型始终为Page ,强制将其强制转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM