0

I want to just reverse the items in this collection, so I decided to require that it be part of Traversable, and any of the subtypes for it, and have it return a Traversable, but I think I may need to use a variance on that also, but, at the moment I get a compiler error, using Scala 2.10.0-M5.

trait Polynomials {
    def coefficients[+A <: Traversable[T]](x:A):Traversable[A] =  x.foldLeft(Traversable[A]())((b,a) => a :: b)

}

These are the errors I am getting, and I am not certain what I did wrong.

Description Resource    Path    Location    Type
']' expected but identifier found.  Polynomials.scala   line 4  Scala Problem
'=' expected but ']' found. Polynomials.scala   line 4  Scala Problem
illegal start of simple expression  Polynomials.scala   line 5  Scala Problem
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
James Black
  • 41,583
  • 10
  • 86
  • 166
  • Is this all the code in Polynomials.scala or are you omitting some code for the sake of berevity? – Emil L Jul 27 '12 at 19:24
  • You need a self contained example. Type `T` is not defined anywhere. Furthermore, you cannot annotate a method's type parameter with a variance, so `+A` doesn't make any sense. A type in a method argument is always in contravariant position (you can call `def m(a: AnyRef)` with a `String` argument, and a return type is always in covariant position (you can treat the result of `def m() : String` as an `AnyRef`. – 0__ Jul 27 '12 at 19:31
  • @EmilH - Actually, at the moment it is just this one function. I will be adding more, but I got myself stuck. – James Black Jul 27 '12 at 20:47

1 Answers1

6

Scala doesn't have use-site variance, so +A is not allowed in a method, only in a class. It doesn't really make sense here anyway; I don't think you'll miss it. Also, you need a T somewhere, either on the trait or on the method. And :: isn't defined on traversable, but a List is a traversable, so you can use one. And you're actually returning a Traversable[T], not a Traversable[A]. So:

trait Polynomials {
  def coefficients[T, A <: Traversable[T]](x: A): Traversable[T] = 
    x.foldLeft(List[T]())((b,a) => a :: b)
}

But the A <: Traversable[T] isn't really buying you anything since subtyping gets you that anyway. So shorter and simpler is

trait Polynomials {
  def coefficients[T](x: Traversable[T]): Traversable[T] = 
    x.foldLeft(List[T]())((b,a) => a :: b)
}
Community
  • 1
  • 1
Rex Kerr
  • 166,841
  • 26
  • 322
  • 407