13

I have the following code that based on the input (args) I want to create a string but the answer is incorrect. I have args(0) is a path, args(1) is an operand like "+", and args(2) is a number (and I want to put space between them:

 //some code .. var Statement="" for (j<-0 to 2) { if (Files.exists(Paths.get(args(j)))){ Statement.concat(inputXml) Statement.concat(" ") } else{ Statement.concat(args(j)) Statement.concat(" ") } println(args(j)) println(Statement) } println(Statement) //some code ... 

the output is a blank! I have used this link as reference. Would you please help me on this I am new in Scala. Thanks.

1
  • 1
    also: a.concat(b) should be written as a+b Commented May 28, 2015 at 19:43

1 Answer 1

17

String.concat returns an entirely new String object. It will not mutate your current Statement variable at all. Now I wouldn't recommend you do the following, but all you technically need to change is reassign Statement to the return value of all your concat calls:

 //some code .. var Statement="" for (j<-0 to 2) { if (Files.exists(Paths.get(args(j)))){ Statement = Statement.concat(inputXml) Statement = Statement.concat(" ") } else{ Statement = Statement.concat(args(j)) Statement = Statement.concat(" ") } println(args(j)) println(Statement) } println(Statement) //some code ... 

A more performant solution would be to use a StringBuilder instead.

val Statement = StringBuilder.newBuilder Statement.append(...) println(Statement.toString) 
Sign up to request clarification or add additional context in comments.

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.