Search code examples
arraysstringgroovy

Converting a String to a String[] yields different results when used in variable definition or as function parameters


I am trying to implement a small function in Groovy, taking a array of String as an input and printing it in a YAML format.

It seems Groovy is converting String variables to String[] in different ways whether it's occurring at variable definition or in the definition of a function parameter.

This curious behavior is shown with the following code snippet:

// #1
println '#1'
def h = 'one'
println h.class
String[] a = h
println a.class
println a.length
println a

// #2
println '#2'
String f(String[] param) {
  println param.class
  println param.length
  println param
}
f(h)

Running with Groovy 2.4.16:

#1
class java.lang.String
class [Ljava.lang.String;
3
[o, n, e]
#2
class [Ljava.lang.String;
1
[one]

I have searched the Groovy spec and didn't find anything explaining this behavior.

Does anybody have an explanation why:

  • passing a String to a String[] variable in a variable definition splits the String to its individual characters,
  • whereas passing a String to a function expecting a String[] parameter will create an array of size 1 with the given string?

I would have expected both situation to yield to the same result.


Solution

  • The second part is not coercing/casting at all; you are using variadic arguments like in Java (the language), which of the underlying JVM has no concept of and always uses arrays.

    The first part would be roughly the cast to array via list