In my previous post, I explained how can we use custom
types in switch statement by overloading isCase method. We can even overload
isCase method to get more flexibility.
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 } boolean isCase(int id){ return 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" } switch(1){ case emp1 : println "emp1 has id 1"; break case emp3 : println "emp3 has id 1"; break default : println "No match found" }
Output
Both emp1 and emp3 has same id
emp1 has id 1
No comments:
Post a Comment