Scala, Extend object with a generic trait

删除回忆录丶 提交于 2019-11-28 01:10:18
Travis Brown

The problem is that you're shadowing the trait's type parameter with the T on the add and get methods. See my answer here for more detail about the problem.

Here's the correct code:

trait Tray[T] {
  val tray = ListBuffer.empty[T]

  def add (t: T) = tray += t      // add[T] --> add
  def get: List[T] = tray.toList  // get[T] --> add
}

object Test extends Tray[Int]

Note the use of extends in the object definition—see section 5.4 of the spec for an explanation of why with alone doesn't work here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!