Thursday, 17 January 2019

Groovy: Spaceship (<=>) operator

Spaceship operator (<=>) delegates the call to compareTo method of the object.

HelloWorld.groovy
public class Employee implements Comparable<Employee>{

    String firstName, lastName;
    Integer salary;
    
    Employee(String firstName, String lastName, int salary){
        this.firstName = firstName;
        this.lastName = lastName;
        this.salary = salary;
    }
    
    @Override
    public int compareTo(Employee o) {
  println "Calling compareTo method"
        if(o == null)
            throw new NullPointerException();
       return this.salary.compareTo(o.salary);
    }
    
    @Override
    public String toString(){
      return salary +". " + firstName +" " + lastName;  
    }
 
}

Employee emp1 = new Employee("krishna", "Gurram", 123456)
Employee emp2 = new Employee("KRISHNA", "GURRAM", 23456)
Employee emp3 = new Employee("KRISHNA", "GURRAM", 123456)

println "emp1 <=> emp2 : ${emp1 <=> emp2}"
println "emp1 <=> emp3 : ${emp1 <=> emp3}"
println "emp2 <=> emp3 : ${emp2 <=> emp3}"


Output

Calling compareTo method
emp1 <=> emp2 : 1
Calling compareTo method
emp1 <=> emp3 : 0
Calling compareTo method
emp2 <=> emp3 : -1



Previous                                                 Next                                                 Home

No comments:

Post a Comment