Andy
Andy

Reputation: 10830

Why can I not use :: after a list to append a string to it in Scala?

So I assume my issue has to do with what is going on under the hood, but I don't understand why this doesn't works:

scala> b = b :: "apple";
<console>:8: error: value :: is not a member of java.lang.String

but this does:

scala> b = "apple" :: b;
b: List[java.lang.String] = List(apple, pear)

Thanks.

Upvotes: 0

Views: 192

Answers (3)

om-nom-nom
om-nom-nom

Reputation: 62835

Another possibility is to explicitly add Nil to the end of chain:

scala> val a = "apple"
a: java.lang.String = apple

scala> val b = "pear"
b: java.lang.String = pear

scala> a::b::Nil
res0: List[java.lang.String] = List(apple, pear)

Upvotes: 0

Luigi Plinge
Luigi Plinge

Reputation: 51109

Method names that end in : are right associative, so b :: "apple" tries to call the :: method on a String, which doesn't exist.

The normal strategy for appending things if you must use a List is to add things to the beginning then reverse the result when you're done. But as Rex says, using a Vector might be better.

Upvotes: 8

Rex Kerr
Rex Kerr

Reputation: 167891

:: always joins a new item to the head of a list. Adding an item to the end can be done, but it takes time proportional to the length of the list (since the entire list must not only be traversed but, actually, also rebuilt).

If you really must add a item to the end of a list, use :+:

List("pear","orange") :+ "apple"

Better yet, use Vector when you need to add to the end (it's much faster at double-ended additions):

Vector("grape","peach") :+ "apple"

Upvotes: 6

Related Questions