Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ListBuffer in scala?

Tags:

scala

I have a situation where I am passing a single element list to a method. Within this method, the single element in the list is incremented by one. So that after method call, the list first element is modified ( incremented by one).

Code is like this:

val ct = List(5)

someMethod(ct)

println (ct(0))

// should print 6

......

//within somethod, I incrment the element like:
def someMethod(ct: List[Int}) {
    ct(0) = ct(0) + 1
}

Of course above code does not work in Scala. I looked at ListBuffer but I find the scala doc hard to follow. Scala doc is divided into 2 groups: Type Members and Value Members. In type member there is class WithFiler and value members has many methods. How can I use WithFiler ( probably not directly related to this question but I want to understand how to make use of scala doc).

ListBuffer seems to be the right solution for this problem if I want to have very high performance (the someMethod is called millions of times) ( correct me if I am wrong).

So how to solve above problem if ListBuffer is the right type of list and if not what is the solution?

like image 782
rjc Avatar asked Jul 04 '11 10:07

rjc


2 Answers

In scala, the expression:

ct(0) = ct(0) + 1

is rewritten as:

ct.update( 0, ct.apply(0) + 1 )

Method update is not defined for supertype List because lists can be immutable. However, that's the type of the function argument.

So you must use only ListBuffers (or a mutable supertype):

def someMethod(ct: ListBuffer[Int]) {
  ct(0) = ct(0) + 1
}

scala> val lst = ListBuffer( 5 )
  lst: scala.collection.mutable.ListBuffer[Int] = ListBuffer(5)
scala> someMethod( lst )
scala> lst
  res2: scala.collection.mutable.ListBuffer[Int] = ListBuffer(6)

By the way, if you need to access elements by indices, use instead an ArrayBuffer. It should work as java ArrayList.

Finally, If you don't need to think about WithFilter stuff. Just use the filter method.

like image 177
paradigmatic Avatar answered Nov 06 '22 16:11

paradigmatic


If performance is a main goal and maximal size of collection is known, you can use Array which maps directly to java array.

like image 31
incrop Avatar answered Nov 06 '22 15:11

incrop