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::Nil
in the function concat
?
myList ::: _
translates to _.:::(myList)
, whereas myList :::
translates to myList.:::(_)
.
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:::x
List[Int]
List
has a :::
methodx.:::(myList)
, which prepends myList
to x
.myList
if of type List[Int]
:::
, so there's no right-associativitymyList
and :::
myList.:::
is the same as x => myList.:::(x)
, which prepends x
to myList
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With