Reputation: 11022
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
Reputation: 37008
it's println((line-"path ").split("/"))
. Otherwise you will attempt to split the result of println, which is nil.
Upvotes: 2
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("/"))
ORline.split(" ")[1].split("/")
Upvotes: 1