When trying to answer this question : Leave off underscore in function literal I tried to code an example and I faced a strange behavior.
scala> val myList = 1::2::Nil
myList: List[Int] = List(1, 2)
scala> def concat:(List[Int]=> List[Int]) = myList:::
concat: (List[Int]) => List[Int]
scala> concat(3::Nil)
res1: List[Int] = List(3, 1, 2)
While I have the good answer when I use _or x=> f(x) syntaxes.
scala> def concat0:(List[Int]=> List[Int]) = x=> myList:::x
concat0: (List[Int]) => List[Int]
scala> def concat1:(List[Int]=> List[Int]) = myList::: _
concat1: (List[Int]) => List[Int]
scala> concat0(3::Nil)
res2: List[Int] = List(1, 2, 3)
scala> concat1(3::Nil)
res3: List[Int] = List(1, 2, 3)
Is there a rational explanation why myList comes after 3::Nilin the function concat?
myList ::: _translates to_.:::(myList), whereasmyList :::translates tomyList.:::(_).tl;dr
This post goes into more detail about right associative methods. What’s happening here is:
def concat0:(List[Int]=> List[Int]) = x=> myList:::xList[Int]Listhas a:::methodx.:::(myList), which prependsmyListtox.myListif of typeList[Int]:::, so there’s no right-associativitymyListand:::myList.:::is the same asx => myList.:::(x), which prependsxtomyList.