Freewind
Freewind

Reputation: 198318

How to use operator `?` to get an item from an array?

Groovy code:

def line = "aa bb"
println line?.split("\\s+")?[1]

I want to use ? for an array to get an item. If the array is null, then return null, just like ?..

But the above code can't be compiled. How to fix it? Or is there any other simple alternative solution to this?

Upvotes: 2

Views: 141

Answers (2)

AlexanderBrevig
AlexanderBrevig

Reputation: 1987

It's the default behavior for List:

println (line?.split("\\s+")as List)[1] 

Upvotes: -1

Adam
Adam

Reputation: 5070

You can use getAt instead of [] (subscript operator)

def line = "aa bb"
println line?.split("\\s+")?.getAt(1)

http://groovyconsole.appspot.com/script/801001

Upvotes: 2

Related Questions