How to Override Operators in Groovy

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.

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 of experience in training, development, and consulting in a variety of technology areas including Python, Java, C, C++, XML, JavaScript, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen has a degree in Computer Science and Physics from Florida State University.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.