1

I'm trying to add element to a List[String] while omitting annoying parenthesis. I tried this:

object Main extends App {
    val l = List("fds")
    val xs1: List[String] = l.+:("123")  // ok
    val xs2: List[String] = l +: "123"   // compile-error
}

DEMO

Why is omitting parenthesis causing compile-error? These assignments look the same to me. What is the difference?

St.Antario
  • 26,175
  • 41
  • 130
  • 318

1 Answers1

6

It's happening because of right associative methods.

scala> val l = List("abc")
l: List[String] = List(abc)

scala> "efg" +: l
res3: List[String] = List(efg, abc)

Read more here What good are right-associative methods in Scala?

Error case

scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)


scala> 4 +: l 
res1: List[Int] = List(4, 1, 2, 3)

scala> l +: 1
<console>:13: error: value +: is not a member of Int
       l +: 1
     ^

Because +: is right associative. Method +: is getting invoked on Int instead of list

In order to make it work we can explicitly invoke method on list without the special operator syntax

scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)

scala> l.+:(1)
res4: List[Int] = List(1, 1, 2, 3)

Above case works because its normal method invocation.

Community
  • 1
  • 1
Nagarjuna Pamu
  • 14,737
  • 3
  • 22
  • 40