Christian Bongiorno
Christian Bongiorno

Reputation: 5648

Groovy Truthy question: String.split() produces empty array, but is 'true' ? How?

Below is a series of steps I have taken in the grooysh shell demonstrate the problem

String.split() => String[] as expected in the Java SDK. When I evaluate this as part of a continuing expression: changedDirs.split('\r\n').collect{ ... } my collect executes 1 time with an empty it. Let me grant: this code is running on a Jenkins server and Jenkins is known to have, let's say, a dialect of groovy running. But, regardless, when I test it locally with groovysh, I indeed get something I didn't expect: [] evaluates to truthy if it comes from String.split()

So: Can someone explain:

  1. How this groovy code below produces a truthy for String.split() and not for a basic empty []
  2. Is Jenkins doing something weird?
groovy:000> [] ? 'true' : 'false'
===> false
groovy:000> changedDirs = ''
===> 
groovy:000> changedDirs.split('\r\n')
===> []
groovy:000> changedDirs.split('\r\n') ? true : false
===> true
groovy:000> result = changedDirs.split('\r\n')
===> []
groovy:000> result ? true : false
===> true
groovy:000> result.class
===> class [Ljava.lang.String;
groovy:000> [] as String[] ? true : false
===> false
groovy:000> 

Upvotes: 1

Views: 1192

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42184

The result evaluates to true as boolean, because changedDirs.split('\r\n') produces String[] array with a single element - an empty string. Take a look at the following example:

groovy:000> ([] as String[]).class
===> class [Ljava.lang.String;
groovy:000> ([] as String[]) ? true : false
===> false
groovy:000> x = ([] as String[])
===> []
groovy:000> x.dump()
===> <[Ljava.lang.String;@5c41d037>
groovy:000> y = "".split(",")
===> []
groovy:000> y.class
===> class [Ljava.lang.String;
groovy:000> y.dump()
===> <[Ljava.lang.String;@79a1728c>
groovy:000> y ? true : false
===> true
groovy:000> y.length
===> 1
groovy:000> x.length
===> 0
groovy:000> y[0].dump()
===> <java.lang.String@0 value= hash=0>
groovy:000> 

In the "Groovy Truth", every non-empty array evaluates to true when calls asBoolean() method, no matter what is the value of the elements in the array.

If you look at the following Java code example, you will see that String.split(pattern) method produces a single element array in case of an empty string.

final class Test {

    public static void main(String[] args) {
        String[] array = "".split("\r\n");

        System.out.println(array.length); // prints: 1
    }
}

This SO question might be useful - Why does "split" on an empty string return a non-empty array?

Upvotes: 4

Related Questions