DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Momento Migrates Object Cache as a Service to Ampere® Altra®
  • Why I Ditched Redis for Cloudflare Durable Objects in My Rate Limiter
  • The Unreasonable Effectiveness of the Actor Model for Creating Agentic LLM Applications
  • Real-Object Detection at the Edge: AWS IoT Greengrass and YOLOv5

Trending

  • 11 Agentic Testing Tools to Know in 2026
  • Scaling Cloud Data Automation: A Practical Guide to Open Table Formats
  • Improving DAG Failure Detection in Airflow Using AI Techniques
  • Detecting Bugs and Vulnerabilities in Java With SonarQube
  1. DZone
  2. Coding
  3. Languages
  4. Groovy Goodness: Easy Object Creation With Tap Method

Groovy Goodness: Easy Object Creation With Tap Method

Want to learn more about object creation in Groovy? Here's how to create an object in Groovy with the tap method.

By 
Hubert Klein Ikkink user avatar
Hubert Klein Ikkink
·
Jun. 14, 18 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
12.8K Views

Join the DZone community and get the full member experience.

Join For Free

Groovy 2.5.0 adds thetap method to all objects and changes the method signature of thewith method. In a previous post, we learned about the with method. In Groovy 2.5.0 we can add an extra boolean argument to thewithmethod. If the value is false, which is the default, thewith method must return the same value as the closure invocation returns. If the value is true, the object instance on which the with  method is invoked will be returned. The new tap method is an alias for with (true), so it will always return the object instance.

In the first example, we will use the tap method to create a new Sample object and set property values to invoke methods of the Sample class:

/**
 * Sample class with some properties
 * and a method.
 */
class Sample {

    String username, email

    List<String> labels = []

    void addLabel(value) {
        labels << value
    }
}

// Use tap method to create instance of
// Sample and set properties and invoke methods.
def sample =
        new Sample().tap {
            assert delegate.class.name == 'Sample'

            username = 'mrhaki'
            email = '[email protected]'
            addLabel 'Groovy'
            addLabel 'Gradle'

            // We use tap, an alias for with(true),
            // so the delegate of the closure,
            // the Sample object, is returned.
        }

assert sample.labels == ['Groovy', 'Gradle']
assert sample.username == 'mrhaki'
assert sample.email == '[email protected]'


In the following example, we will use the with method to demonstrate the differences for several invocations using different argument values:

/**
 * Sample class with some properties
 * and a method.
 */
class Sample {

    String username, email

    List<String> labels = []

    void addLabel(value) {
        labels << value
    }

}

// Use with method to create instance of
// Sample and set properties and invoke methods.
def sample1 =
        new Sample().with {
            assert delegate.class.name == 'Sample'

            username = 'mrhaki'
            email = '[email protected]'
            addLabel 'Groovy'
            addLabel 'Gradle'  
        }

// With method returns the result
// from the closure. In the previous
// case the return result is null,
// because the last statement addLabel
// is used as return value. addLabel has
// return type void.
assert !sample1


// Use with method to create instance of
// Sample and set properties and invoke methods.
def sample2 =
        new Sample().with {
            assert delegate.class.name == 'Sample'

            username = 'mrhaki'
            email = '[email protected]'
            addLabel 'Groovy'
            addLabel 'Gradle'

            // Explicitly return delegate of
            // closure, which is the Sample object.
            return delegate
        }

assert sample2.labels == ['Groovy', 'Gradle']
assert sample2.username == 'mrhaki'
assert sample2.email == '[email protected]'


// Use with method to create instance of
// Sample and set properties and invoke methods.
def sample3 =
        new Sample().with(true) {
            assert delegate.class.name == 'Sample'

            username = 'mrhaki'
            email = '[email protected]'
            addLabel 'Groovy'
            addLabel 'Gradle'

            // We use with(true), so the
            // delegate of the closure, the Sample
            // object, is returned.
        }

assert sample3.labels == ['Groovy', 'Gradle']
assert sample3.username == 'mrhaki'
assert sample3.email == '[email protected]'


A good use case for using the with method is to transform an object to another type using values from the object. In the next example, we use values from a Sample object to create a new String:

/**
 * Sample class with some properties
 * and a method.
 */
class Sample {
    String username, email
    List<String> labels = []
    void addLabel(value) {
        labels << value
    }
}

def sample =
        new Sample().tap {
            username = 'mrhaki'
            email = '[email protected]'
            addLabel 'Groovy'
            addLabel 'Gradle'
        }

// The with method can be very useful to
// transform object to another type using
// values from the object.
def user = sample.with { "$username likes ${labels.join(', ')}." }

assert user == 'mrhaki likes Groovy, Gradle.'


Written with Groovy 2.5.0.

Object (computer science) Groovy (programming language)

Published at DZone with permission of Hubert Klein Ikkink. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Momento Migrates Object Cache as a Service to Ampere® Altra®
  • Why I Ditched Redis for Cloudflare Durable Objects in My Rate Limiter
  • The Unreasonable Effectiveness of the Actor Model for Creating Agentic LLM Applications
  • Real-Object Detection at the Edge: AWS IoT Greengrass and YOLOv5

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook