上类型边界优于子类型的优势 [英] Advantage of Upper Type Bound over Subtyping

查看:35
本文介绍了上类型边界优于子类型的优势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个例子中,使用类型上限比只使用类型有什么优势?

What is the advantage of using upper type bounds over just type in this example?

为什么人们喜欢这个

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

在此之上:

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
}

:更精确的类型,允许您不混淆Page的不同子类型,无需强制转换即可访问MyPage的操作等

: more precise types, allowing you not to mix up different subtypes of Page, to access operations of MyPage without casting, etc.

另外,如果你有第一个而需要第二个,你可以使用 Pages[Page];如果你有第二个并且需要第一个,那你就不走运了.

Also, if you have the first and need the second, you can just use Pages[Page]; if you have the second and need the first, you are out of luck.

这篇关于上类型边界优于子类型的优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆