red888
red888

Reputation: 31694

How do I define an entire object and methods on single line

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

Answers (1)

cfrick
cfrick

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

Related Questions