How to Override Operators in Groovy

  • google plus

In Brief...

Sometimes you might want to change the implementation of an operator in Groovy. For example, you might alter the implementation of string concatenation (i.e., "add") to automatically add a space between the two string. You can accomplish this task by overriding the plus operation for strings. We will implement this scenario below.

Instructions

To override operators in Groovy, follow these six steps.

  1. Open your text editor and create the Groovy class that implements the override:
    
    class OverrideStringConcat {
    	static String plus (String s1, String s2) {
    		s1.toUpperCase() << " " << s2.toUpperCase()
    	}	
    }
    
    You are creating a class named OverrideStringConcat. The plus method provides the logic to override the default implementation of concatenating one string to another. The method returns a string that is the concatenation of the two input strings with a space inserted between the strings. To add more interest to our scenario, the input strings are converted to upper case as well.
  2. Save your file as OverrideStringConcat.groovy.
  3. Open a command prompt and navigate to the directory containing your new Groovy class. Then type in the command to compile your source:
    Compile Groovy override
  4. In your text editor, create the tester:
    	
    import OverrideStringConcat
    def fullName = "Stephen" + "Withrow"
    println "Name using standard string concatenation: $fullName"
    use (OverrideStringConcat) {	
    	fullName = "Stephen" + "Withrow"
    	println "Name using override on string concatenation: $fullName"
    }
    
    The import statement is used to resolve the reference to OverrideStringConcat on the use statement. Within the scope of the use statement, the override will be applied when the first name and last name are concatenated. Overall, two concatenations are performed, one using the default concatenation operation and another using the customized concatenation.
  5. Save your file as TestConcatOverride.groovy.
  6. In the command prompt, type in the command to interpret and run your script:
    Run override tester
    Note that the program displays the default concatenation and then the results of using the customized concatenation.

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss