openlang

Preferred approach for making a shallow duplicate of a Groovy map

I need to create a shallow duplicate of a map inside my script, allowing me to change one of its keys afterwards. The spread operator provides one approach. But this runs inside a Jenkins pipeline, and our organization's policy disallows that operator.

Calling the clone() method succeeds, though Intellij reports "Access to 'clone' exceeds its access rights". This is partly due to the map having been created through Jenkins readJSON, which might supply a map-like object that doesn't implement the clone() method itself.

Which approach, excluding the spread operator, is most idiomatic for shallow map copying?

The conversation continues 2

Follow the reasoning
  1. Permalink

    Try collectEntries(Closure.IDENTITY) - maps don't offer a parameterless overload, so you'll need to supply an identity function of some sort

  2. Permalink

    I've discovered a briefer way of making a shalow map copy. Just combine the existing map with an empty one. Here's an example.

    
    def baseline = [left: 2, right: 2]
    
    def duplicate = baseline + [:]
    
    assert duplicate == baseline
    assert !duplicate.is(baseline)

Other sides of the same question

  1. Missing field through a derived table in SQL

    I'm executing the following SQL statement: It produces the following error: #1054 - Unknown column 'shipping.post_id' in 'on…

    Replies 2Latest activity sql
  2. Testing D arrays for a matching entry

    with associative arrays this is possible how is this done with ordinary arrays? I'd like a validation expression, for example

    Replies 2Latest activity d
  3. Removing an optional column safely with PostgreSQL 9+

    I want to remove a column belonging to a table. What's the way to determine whether that column is present? I read the manual…

    Replies 2Latest activity sql