Adding elements to global list object in scala -
allright guys, pardon me if question has been asked. yet scala newbie question. example if want have global list object can used place holder container, in java can 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 element } similarly, if simulate same syntax in scala - end java.lang.indexoutofboundsexception: 0. how can 1 achieve similar 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 element }
to strictly answer question:
private var strlist: list[string] = nil def add(el: string) { strlist = el :: strlist; } you using wrong operator. need use ::. , need update inline because list of immutable length.
i'm switching el , strlist because :: right associative, means method comes object right of :: operator.
also, :: operator perform prepend, means elements in reverse order.
you can either call reverse @ end(before usage etc) or if want semantically similar java arraylist perhaps consider scala listbuffer, mutable collection can append.
import scala.collection.mutable.listbuffer; private var strlist: listbuffer[string] = nil def add(el: string) { strlist += el; }
Comments
Post a Comment