Hello friends,
I have some groovy tricks to share with you. 😉

  • Direct field access operator(@)

    We always write a groovy class containing property and there getters. So I am taking a simple example here to make you know the benefit of this operator.

    class User {
        public final String name                 
        User(String name) { this.name = name}
        String getName() { "Name: $name" }       
    }
    def user = new User('Tinku Saini')
    assert user.name == 'Name: Tinku Saini'  
    

    In the above-given code snippet, we have a class having a property which contains its getter method. A constructor just for creating an object because I have defined the property final non-static.

    I have prefixed ‘Name:’ as an extra string to the name saved in the created object to the getter method of name. By doing this, I just want to make you know that groovy will call the getter method of name instead of property name as in Java.
    So user.name will return the ‘Name: Tinku Saini’. Now the question is that how we will get access to the property of an object instead of getter or How we bypass the getter and directly use the property of an object?
    Here is the groovy way to do this:-

    assert user.@name == 'Tinku Saini'
    

    By suffixing the ‘@’ operator to the property of an object you can bypass the getter method of that property.

  • Method pointer operator(&)

    This is a beautiful feature of groovy by which we can store the reference to a method calling. Code will explain you how it will happen:-

    def message = 'i love groovy.'            
    def methodRefrence = str.&toUpperCase  
    assert 'I LOVE GROOVY.' == methodRefrence()
    

    In above code snippet, we are storing ‘toUpperCase()’ method of String class into a variable named ‘methodRefrence’ and call it later.
    Hope It helps you. Thanks ! 😀