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
}
Listappears to be totally the wrong collection for your purposes - you should use aVector, which has both fast append and prepend, and is the standard implementation of an indexed collection for fast lookup. You can writestrVector = strVector :+ el, or the short versionstrVector :+= el.