Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - isCase Method



isCase method is a very important part of Groovy's powerful switch statement and in operator. It allows to customize switch statement for custom objects.

How isCase method works

switch statement in Groovy implicity calls isCase() method to check if a value matches a given case or not. in operator also uses the isCase() method to determine whether the given value is contained within the collection on the right side or not.

Default Implementation of isCase() method

  • StringisCase() method uses equals() method to compare string values.

  • RangeisCase() method checks if value is within range.

  • Class − For a custom object, isCase() checks if the object is instance of that particular class.

  • PatternisCase() method performs a match against the value.

Customizing isCase() method Behavior

We can customize isCase() method to act as per our logic by implementing isCase(value) method in our class. Whenever Groovy finds an object in a case block or on left side of in operator, Groovy looks for isCase(value) method implementation and executes the same.

Following is an example of having a customize case to match Employee objects by their name.

Example.groovy

class Employee {
   String name

   // implement isCase() method
   boolean isCase(String value) {
      return name.equalsIgnoreCase(value)
   }

   @Override
   String toString() {
      return "Employee (name: $name)"
   }
}

def julie = new Employee(name: "Julie")
def robert = new Employee(name: "Robert")

def name = "julie"

switch (name) {
   case julie:
      println "$name is present as ${julie.name}"
      break
   case robert:
      println "$name is present as ${robert.name}"
      break
   default:
      println "Not found"
}

Output

When we run the above program, we will get the following result.

julie is present as Julie

Following is an example of having a customize in operator to check Employee object by their name.

Example.groovy

class Employee {
   String name

   // implement isCase() method
   boolean isCase(String value) {
      return name.equalsIgnoreCase(value)
   }

   @Override
   String toString() {
      return "Employee (name: $name)"
   }
}

def julie = new Employee(name: "Julie")
def robert = new Employee(name: "Robert")

def name = "julie"


if (name in julie) {
   println "'$name' is present"
}else {
   println "Not found."
}

Output

When we run the above program, we will get the following result.

'julie' is present
Advertisements