1

I want to iterate over a list of strings, concatenate them with the suffix/prefix "" and if it's not the last entry of the list append a comma at end.

Wanted Output example: "circle","cube","banana"

My first try is the following snippet:

@listStringifier(list: List[String]) = @{
  if (list != null && !list.isEmpty) {
   for ((string, index) <- list.zipWithIndex){if(index != list.size-1){"string",}
   else{"string"}
   }
  }
}

But this function is always empty when I use @listStringifier anywhere.

Logging within the @listStringifier block shows that it is iterating, but not assigning anything.

If I call the for loop directly in the template like this following snippet it works:

@if (list != null && !list.isEmpty) {
  for ((string, index) <- list.zipWithIndex){if(index != list.size-1){"@string",}
  else{"@string"}
  }
}

But I dont want to iterate several times so I want to assign the concatenated string to a variable afterwards.

Any help would be appreciated, thanks in advance

2 Answers 2

3

I think mkString can do what you want

list.mkString( "'" , "','" , "'" )
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for mentioning, that was exactly what I'm looking for so I replaced the single quotation mark with the double quotation marks and it worked like a charm. Like this: list.mkString( "\"" , "\",\"" , "\"" ) Thank you for your help
Yeah, I put single quotes to not go crazy on the escape sequences (is there a way in Scala to have alternative String delimiters like Perl's q{","}?)
I don't know mate, sorry
1

mkString can do this elegantly

@listStringifier(list: List[String]) = @{ list mkString("", ",", "") }

if you want quotes around the strings you could do

list.map(str => s""""$str"""").mkString(",")

4 Comments

(""""""", """" ,"""", """"""") was requested.
thanks for mentioning, I tried this before, but that would only append the quotes to the very first and last sign unfortunately.
@Yeti: You can add the quotes to the separating comma as well to work around that.
@Thilo as mentioned in your answer it works now, thank you all for your help. I cannot mark both answers as correct, indeed they are from the point of syntax

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.