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?
In scala, the expression:
is rewritten as:
Method
updateis not defined for supertypeListbecause lists can be immutable. However, that’s the type of the function argument.So you must use only ListBuffers (or a mutable supertype):
By the way, if you need to access elements by indices, use instead an
ArrayBuffer. It should work as javaArrayList.Finally, If you don’t need to think about
WithFilterstuff. Just use thefiltermethod.