Reputation: 12538
Allright guys, pardon me if this question has already been asked. Yet another Scala newbie question. So for example if I want to have a global List object which can be used as a place holder container, in Java I can easily do;
//share list object
private List<String> strList = new ArrayList<>();
void add(String el)
{
strList.add(e);
}
static void main(String[] args) {
{
add("36 Chambers");
out.println(strList.get(0));//assume only element
}
Similarly, if I simulate the same syntax in Scala - I end up with java.lang.IndexOutOfBoundsException: 0
. How can one achieve similar with simple Scala?
private var strList: List[String] = Nil
def add(el: String) {
strList :+ el
}
def main(args: Array[String]) {
add("36 Chambers")
println(s(0)) //assume only element
}
Upvotes: 2
Views: 1040
Reputation: 28511
To strictly answer your question:
private var strList: List[String] = Nil
def add(el: String) {
strList = el :: strList;
}
You are using the wrong operator. You need to use ::
. And you need to update inline because a List
is of immutable length.
I'm switching the el
and strList
because ::
is right associative, which means the method comes from the object to the right of the ::
operator.
Also, the ::
operator will perform a prepend, which means your elements will be in reverse order.
You can either call reverse at the end(before usage etc) or if you want something semantically similar to a Java ArrayList
perhaps consider a Scala ListBuffer
, a mutable collection to which you can append.
import scala.collection.mutable.ListBuffer;
private var strList: ListBuffer[String] = Nil
def add(el: String) {
strList += el;
}
Upvotes: 1