Reputation: 31694
This throws an error (can't set on null object)
def currentBuild = [:].rawBuild.getCauses = { return 'hudson.model.Cause$UserIdCause@123abc' }
I need to do it on multiple lines like this
def currentBuild = [:]
currentBuild.rawBuild = [:]
currentBuild.rawBuild.getCauses = { return 'hudson.model.Cause$UserIdCause@123abc' }
Is there a terse way to define this object on a single line or statement? I don't understand why my single line attempt doesn't work.
Upvotes: 0
Views: 358
Reputation: 37073
Instead of chaining setters, I'd just use a map literal with the nested values. E.g.
def currentBuild = [rawBuild: [getCauses: { return 'hudson.model.Cause$UserIdCause@123abc' }]]
println currentBuild.rawBuild.getCauses()
// → hudson.model.Cause$UserIdCause@123abc
If you have to go more imperative instead of declarative, have a look at
.get(key, fallback)
, .withDefault{ ... }
, .tap{ ... }
.
BTW: those are not objects but just maps.
Upvotes: 1