2

I have a function with input params: Number and list of strings, e.g: (1, ListString)

And i need it to return a new list of strings that looks like:

[["1","name1"], ["1","name2"]] 

For each string in my input string list, i need to place it in that structure, so i've build the following:

def buildStringForproductsByCatView(tenantId:String, cat:List[String]):List[String]= { var tempList= List[String]()//(cat.foreach(x => "[[\"1\",\""+x+"\"]]")) cat.foreach(x => println(("[[\"1\",\""+x+"\"]]"))) cat.foreach(x => tempList + ("[[\"1\",\""+x+"\"]]")) println(tempList.mkString(",")) tempList } 

The list does not fill with items, i tried several ways, but could not get it.

The print line works fine, i am getting this:

[["1","1"]] [["1","cat1"]] 

I just want to add them to a new list of string..

3 Answers 3

2

There are two wrong things in your code.

First one, to append an item to List you should use :+. + is not what you are looking for. tempList + "asd" implicitly converts the list to a String and appends the text to this string. This might be confusing.

The second one, List is immutable, so each :+ call returns you a new List.

So your code should look like this:

x => tempList = tempList :+ ("[[\"1\",\""+x+"\"]]") 
Sign up to request clarification or add additional context in comments.

Comments

2

Although two other answers are technically right, I fail to understand why you don't use map:

def buildString4ProductsByCatView(tenantId:String, cat:List[String]) = { cat.foreach(x => println(("[[\"1\",\""+x+"\"]]"))) cat.map(x => "[[\"1\",\"" + x + "\"]]") } 

2 Comments

The answer to your question is -> I am new to scala.. :) !
Then, take a look at string interpolation feature, and triple quotes -- it might save you from excessive use of escaping and make that string a bit readable (although it's a matter of taste in your case): s"""[["1" , "$x"]]"""
0

Solution was to use ListBuffer[String] with append and finally toList:

def buildStringForproductsByCatView(tenantId:String, cat:List[String]):List[String]= { cat.foreach(x => println(("[[\"1\",\""+x+"\"]]"))) val langItems = ListBuffer[String]() cat.foreach(x => langItems.append(("[[\"1\",\""+x+"\"]]"))) langItems.toList } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.