1

I am new to Scala and have some question about why string::List() works List()::s doesn't?I also want to know if ListBuffer works better than ::?

val columnNames :List[String] = ['foo','bar']
val work :List[String] = List()
for (s <- columnNames) {
  s match {
     //this doesn't compile
     //case workPattern => work :: s
     //this works        
     case workPattern => s :: work
     // this also works
     case workPattern => work :: List(s)
}
0

2 Answers 2

4

a :: b literally means "add an element a at the beginning of a list b". It creates new list with a as a head and b as a tail.

To append element to list you can use ++ or something like this work ::: "foo" :: Nil, the latter isn't very efficient, of course.

For the second part of a question, as stated in the documentation:

Time: List has O(1) prepend and head/tail access. 
Most other operations are O(n) on the number of elements in the list. 
This includes the index-based lookup of elements, length, append and reverse.
Space: List implements structural sharing of the tail list. 
This means that many operations are either zero- or constant-memory cost.

So it depends on size and types of operations you need to perform which is preferable performance-wise.

Sign up to request clarification or add additional context in comments.

Comments

1

The function you call at s :: work is List.::. Scala String is just an alias for Java's string, hence does not expose operators such as ::. s :: work is equivalent to work.::(s).

For more information you can refer How to add elements to a List in Scala (List, ListBuffer) and Scala List class examples: range, fill, tabulate, appending, foreach, more ... by the great Alvin Alexander.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.