Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala, Extend object with a generic trait

I'm using Scala and I want to extend a (singleton) object with a trait, which delivers a data structure and some methods, like this:

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

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

And then I'll would like to mix-in the trait into an object, like this:

object Test with Tray[Int]

But there are type mismatches in add and get:

Test.add(1)
// ...

How can I'll get this to work? Or what is my mistake?

like image 466
Themerius Avatar asked Dec 24 '12 16:12

Themerius


1 Answers

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.

like image 86
Travis Brown Avatar answered Oct 27 '22 04:10

Travis Brown