0

I have the following java program which is not getting compiled:

public class HelloWorld {
  public static void funcA (String... params) {
    funcB(params, "a", "b");
  }

  public static void funcB (String... params) {}

  public static void main(String[] args) {
      funcA("a", "b");
  }

}

The compile error is as follows:

HelloWorld.java:4: error: method funcB in class HelloWorld cannot be applied to given types;
    funcB(params, "a", "b");
    ^
  required: String[]
  found: String[],String,String
  reason: varargs mismatch; String[] cannot be converted to String
1 error

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':compileJava'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 709ms

What am I doing wrong?

Ankit Shubham
  • 2,989
  • 2
  • 36
  • 61

1 Answers1

-1

Turns out that I was slightly misunderstanding the concept of varargs in java. Varargs act just like a Java array. So, when I am calling funcB(params, "a", "b");, the signature is actually (String[], String, String) whereas earlier, I was assuming it to be (String...).

The confusion arose because params in funcA's parameter is having a signature of (String...) and so, when it gets propagated to funcB like funcB(params, "a", "b"); it would have a signature of (String..., String, String) which would mean (String...)

The correct program can be written by squishing params, "a" and "b" into another array and then passing that newly created array in funcB; something like below:

import java.util.Arrays;

public class HelloWorld {
  public static void funcA (String... params) {
    int paramsLength = params.length;
    String[] finalParams = Arrays.copyOf(params, paramsLength + 2);
    finalParams[paramsLength] = "a";
    finalParams[paramsLength+1] = "b";
    funcB(finalParams);
  }

  public static void funcB (String... params) {}

  public static void main(String[] args) {
      funcA("a", "b");
  }

}
Ankit Shubham
  • 2,989
  • 2
  • 36
  • 61
  • @mypetlion In SO, there is an option to "Answer your own question" which is available while you are asking a question. The idea is to share the knowledge and help others if you already know the answer rather than just keeping it to yourself. – Ankit Shubham Jan 09 '20 at 01:40