user972946
user972946

Reputation:

Why does "a".::(List()) report error ":: is not member of string"?

See this:

scala> 1 + 1
res0: Int = 2

scala> 1.+(1)
warning: there were 1 deprecation warning(s); re-run with -deprecation for details
res1: Double = 2.0

scala> "a" :: List()
res2: List[String] = List(a)

scala> "a".::(List())
<console>:8: error: value :: is not a member of String
              "a".::(List())
                  ^

Why does the error occur?

Upvotes: 1

Views: 2886

Answers (3)

4lex1v
4lex1v

Reputation: 21557

Because of operator precedence. In Scala methods which ends with : are right associative. So you should call List().::("a")

If you want to use left associative method then you should write List("a") ++ List(), but that's not always a good choice, cause it has linear execution time

Upvotes: 1

rarry
rarry

Reputation: 3573

Try this

List().::("a")

The reason is that :: is a method of List.

From ScalaByExample:

Like any infix operator, :: is also implemented as a method of an object. In this case, the object is the list that is extended. This is possible, because operators ending with a ‘:’ character are treated specially in Scala. All such operators are treated as methods of their right operand. E.g.,

x :: y = y.::(x) whereas x + y = x.+(y) 

Note, however, that operands of a binary operation are in each case evaluated from left to right. So, if D and E are expressions with possible side-effects,

D :: E 

is translated to

{val x = D; E.::(x)}

in order to maintain the left-to-right order of operand evaluation.

Upvotes: 8

om-nom-nom
om-nom-nom

Reputation: 62835

In scala methods which ends with : got applied in reverse order.

So when you write a::list it is actually list.::(a). String doesn't have :: method, so the solution is to write List().::("a") or Nil.::("a")

Upvotes: 1

Related Questions