$ cat go.scala object Main extends App { Set(1,2,3).toIndexedSeq sortBy (-_) }
$ fsc -d go go.scala
go.scala:1: error: missing parameter type for expanded function ((x$1)
=> x$1.unary_$minus)
object Main extends App { Set(1,2,3).toIndexedSeq sortBy (-_) }
^
go.scala:1: error: diverging implicit expansion for type scala.math.Ordering[B]
starting with method Tuple9 in object Ordering
object Main extends App { Set(1,2,3).toIndexedSeq sortBy (-_) }
^
This version works:
object Main extends App { Set(1,2,3).toSeq sortBy (-_) }
As does this:
object Main extends App { val xs = Set(1,2,3).toIndexedSeq; xs sortBy (-_) }
The latter case makes this look similar to this question (but possibly
not the same):
http://stackoverflow.com/questions/5544536/type-inference-on-set-failing
I didn't find the answers particularly helpful. What does the
variable assignment do that makes this solvable / what does the
absence of the assignment do that makes this unsolvable? Why does
toSeq work but not toIndexedSeq? I tried inspecting the output of
-Ytyper-debug but that led nowhere fast. What exactly am I looking
for here? Thanks for any tips in understanding what's going on.
Now, why toIndexedSeq takes a type parameter (but toSeq doesn't), that
is a good question.
--
Daniel C. Sobral
I travel to the future all the time.
It sounds like the inability to infer types for the no-assignment code
is something that could be eventually fixed - is this probable?
There are a few methods with similar characteristics, such as toBuffer
and toSet. These methods cannot work in any other way, because the
collections are invariant, while TraversableOnce is co-variant, which
causes an invariant/co-variant violation. IndexedSeq, however, is
co-variant (like Seq), so it _could_ benefit from the removal of the
type parameter. I have opened a ticket asking precisely that, and I
_did_ try to compile Scala without the type parameter on toIndexedSeq,
and that works just fine.
So, it is possible.
Sorry, what I was referring to was the more general problem of
inferring types on generic methods without having to insert an
intermediate assignment, not the fact that toIndexedSeq is
unnecessarily generic. The former is something that can be solved,
no?
(For anyone else curious why e.g. Set isn't also covariant since
they're immutable:
http://stackoverflow.com/questions/676615/why-is-scalas-immutable-set-not-covariant-in-its-type)
Ah, ok. Don't get your hopes high: solving this is rather complex, and
may well significantly slow down the compiler, so there's a rather
high cost for very little gain.