Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do string concatenation in Scala

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.

like image 355
Rubbic Avatar asked May 28 '15 19:05

Rubbic


1 Answers

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)
like image 119
Karl Avatar answered Sep 27 '22 17:09

Karl