Scala docs implicit conversion uses ->

I am trying to understand some notation in the Scala docs. Particularly the signature for the List.flatten method. It takes an implicit argument that I assume is supposed to function like a typeclass CanIterate[A, B]. Then, internally, flatten iterates through all the items in each element and adds them to the new, flattened list (or if the list wasn’t nested to begin with, the implicit argument won’t be available, and you’ll get a compiler error). The full signature is:

override def flatten[B](implicit toIterableOnce: A -> IterableOnce[B]): List[B]

The part that confuses me is -> rather than =>. If there were an implicit function from A to IterableOnce[B], I would be happy. But my understanding is that -> is syntactic sugar for making a pair, so we’re getting an implicit tuple with type (A, IterableOnce[B]). I don’t see how that could help with the conversion. I see the same syntax for lots of other implicit parameters.

Am I not understanding the syntax? Can such a pair somehow be used for the conversion? Is there an error in the docs, and it really should be =>?

Any help is appreciated!

1 Like

-> is a pure function, Pure Function Syntax - it’s here because stdlib is compiled with capture checking enabled, but for user, by default it’s effectively normal => function

We should add a switch allowing to disable the capture checking syntax

3 Likes

Yeah – I was in the middle of giving the same answer, but I’m surprised to see this experiment leaking into the stdlib docs yet.

1 Like

I see. That’s pretty cool! Especially if the compiler can enforce it some day.

Is a -> b still syntactic sugar for (a, b)? And if so, how does the compiler know when it’s actually a pure function instead of a pair? Is it when a and b are types?

Basically yes,
When in a type context (not formal name) like F[here] or x: here =, -> means “pure function”
So it’s not really about a and b
This is because some text is both a valid type and a valid expression, the simplest being 0
Therefore 0 -> 1 can be both the literal (0, 1) and the type of pure functions which take 0 and return 1, depending on the context