Groovy allows custom objects to be tested against switch
statement. A custom object can be used in switch case, only if it implements
isCase method.
HelloWorld.groovy
class Employee{ int id String name Employee(int id, String name){ this.id = id this.name = name } boolean isCase(Employee emp) { return emp.id == this.id } } emp1 = new Employee(1, "Krishna") emp2 = new Employee(2, "Ram") emp3 = new Employee(1, "Ram") switch(emp1){ case emp2 : println "Both emp1 and emp2 has same id"; break case emp3 : println "Both emp1 and emp3 has same id"; break default : println "No match found" }
Output
Both emp1 and emp3 has same id
Groovy even enhances all the types by implementing isCase
method. You can check the type of a variable using switch statement.
HelloWorld.groovy
a = 10.1 switch(a){ case Integer : println "$a is of type integer"; break case Float : println "$a is of type Float"; break case Double : println "$a is of type Double"; break case BigDecimal: println "$a is of type BigDecimal"; break default : println "Do not match to any type" }
Output
10.1 is of type BigDecimal
You can even pass ranges to the switch statement.
HelloWorld.groovy
a = 10 switch(a){ case 0..5 : println "$a is in range of (0..5)"; break case 5..10 : println "$a is in range of (5..10)"; break default : println "Do not match to any type" }
Output
10 is in range of (5..10)
You can even use closures, regular expressions and any
custom type that implements isCase method as case statement in switch.
HelloWorld.groovy
a = 10 switch(a){ case 0..5 : println "$a is in range of (0..5)"; break case {it % 3 == 0} : println "$a is divisible by 3"; break case ~/.../ : println "$a is a 3 digit number"; break case Integer : println "$a is of type Integer"; break default: println "Do not match to any case"; break }
Output
10 is of type Integer
No comments:
Post a Comment