2

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
  } 
2
  • Won't bother writing an answer since you've already accepted one, but List appears to be totally the wrong collection for your purposes - you should use a Vector, which has both fast append and prepend, and is the standard implementation of an indexed collection for fast lookup. You can write strVector = strVector :+ el, or the short version strVector :+= el. Commented May 15, 2013 at 0:41
  • @LuigiPlinge please add an answer - this helps others to easily dig and find relevant answers like yours. I will give you a vote up. Commented May 15, 2013 at 8:32

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

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.