Search code examples
groovy

Groovy doesn't print the string inside a function


I am new to groovy. I have the following code where I want to print the Strings on the console, which doesn't work:

import java.io.FileWriter;
import java.util.Arrays;
import java.io.Writer;
import java.util.List;

//Default separator
char SEPARATOR = ',';

//get path of csv file (creates new one if its not exists)
String csvFile = "c:";
println "========================= csvFile";
println csvFile;

String[] params = {"hello"};


writeLine(params, SEPARATOR);

//function write line in csv
public void writeLine(String[] params, char separator)
{
   boolean firstParam = true;
   println params;
   StringBuilder stringBuilder = new StringBuilder();
   String param = "";

   for (int i = 0; i < params.length; i++)
   {
      //get param
      param = params[i];
      println param;

         //if the first param in the line, separator is not needed
       if (!firstParam) 
       {
           stringBuilder.append(separator);
       }

         //Add param to line
       stringBuilder.append(param);

       firstParam = false;
   }

   //prepare file to next line
   stringBuilder.append("\n");
   //add to file the line
   println stringBuilder.toString();

}

It gives the following output:

enter image description here


Solution

  • in groovy to declare array you have to use square brackets:

    String[] params = ["hello"]
    

    btw whole code could be simplified to this:

    String[] params = ["hello"]
    
    def writeLine(params, separator=','){
        println params.join(separator)
    }
    writeLine(params)