rdmueller
rdmueller

Reputation: 11022

Groovy Null-Pointer Riddle :-)

This is more a riddle than a question since I already know the answer, but I thought that maybe some other devs might enjoy this :-)

Imagine you need to put a string like to following apart:

def line = "path /some/path/to/somewhere/test.txt"

and you want to get only the file name. Somehow you start with code like this:

println line-"path "
==> /some/path/to/somewhere/test.txt

works great - let's split the remaining part:

println (line-"path ").split("/")

but now you get

java.lang.NullPointerException: Cannot invoke method split() on null object

you've seen before that line-"path " is not null, so you give it another try

def temp = line-"path "
println temp.split("/")
==> [, some, path, to, somewhere, test.txt]

that works! What's going on?

Are you able to avoid the temp-variable and write the above statement as one-liner?

Upvotes: 0

Views: 285

Answers (2)

cfrick
cfrick

Reputation: 37008

it's println((line-"path ").split("/")). Otherwise you will attempt to split the result of println, which is nil.

Upvotes: 2

rxn1d
rxn1d

Reputation: 1266

Works good for me. No NullPointerException:

def line = "path /some/path/to/somewhere/test.txt"
def temp = line-"path "
println temp.split("/")

Your one-liner would be:

println ((line-"path ").split("/")) OR line.split(" ")[1].split("/")​​​

Upvotes: 1

Related Questions