The :: method in Scala is defined in scala.collection.immutale.List. But when I do this the :: method must be looked up in String or any of its super classes:
val myList = “A” :: “B” :: Nil
I had a look in classes String, Any, AnyRef that all do not define the :: method. When I debug through “A” :: “B” the debugger jumps right into the :: method in List although the receiver object “A” is a String and not a List.
So there seems to be some magic going on here. Maybe :: in List is invoked by some redirection using an implicit? If someone could explain this to me. Thank you.
It’s not a magic, but rather an infix syntax. In Scala 2 it was always available, in Scala 3 there would be additional infix
keyword on a def ::
The case class ::
extends List so also provides the exctractor (unapply method) scala/src/library/scala/collection/immutable/List.scala at 3f09bfff95dc54c0199070312672a0ec32d7b55b · scala/scala · GitHub
def ::
is a method of List itsefl scala/src/library/scala/collection/immutable/List.scala at 3f09bfff95dc54c0199070312672a0ec32d7b55b · scala/scala · GitHub
1 Like
In fact, since ::
is symbolic, the infix
modifier is not needed.
1 Like
The language specs say that if a method ends on :
it is called on the right-hand side rather than the left-hand side.
So the expression:
val list = 1 :: 2 :: 3 :: Nil
Is just sugar syntax for:
val list = Nil.::(3).::(2).::(1)
4 Likes
The answer from BalmungSan explains it. I tried it out:
class Foo:
def ===:[A](bar: A) : String = “foo-” + bar.toString
When running this:
val fooString = “baz” ===: Foo()
println(fooString)
val fooInt = 123 ===: Foo()
println(fooInt)
I get:
foo-baz
foo-123
Thanks, BalmungSan 
3 Likes