Search code examples
scalasingletonextendtype-mismatchtraits

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?


Solution

  • 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.