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

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

How are you handling the data revolution? We want your take on what's real, what's hype, and what's next in the world of data engineering.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • Clean Unit Testing
  • The Unreasonable Effectiveness of the Actor Model for Creating Agentic LLM Applications
  • Real-Object Detection at the Edge: AWS IoT Greengrass and YOLOv5
  • Monitoring and Managing the Growth of the MSDB System Database in SQL Server

Trending

  • Top Trends for Data Streaming With Apache Kafka and Flink
  • Build Your Private Cloud at Home
  • Design Guards: The Missing Layer in Your Code Quality Strategy
  • Apache Cassandra With Java: Introduction to UDT
  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.5K 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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Clean Unit Testing
  • The Unreasonable Effectiveness of the Actor Model for Creating Agentic LLM Applications
  • Real-Object Detection at the Edge: AWS IoT Greengrass and YOLOv5
  • Monitoring and Managing the Growth of the MSDB System Database in SQL Server

Partner Resources

×

Comments

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: