Thursday, 17 January 2019

Groovy: Specify ranges to custom types


You should perform two steps to make the range operator available to custom type.
a.   Custom type must implement next and previous methods.
b.   Custom type must implement Comparable interface

For example, I had written an EvenNumber class that prints even numbers.

HelloWorld.groovy
class EvenNumber implements Comparable<EvenNumber>{
 int num
 int current
 
 public EvenNumber(int num){
  if(num % 2 != 0){
   this.num = num + 1
   return
  }
  this.num = num
  this.current = this.num
 }

 EvenNumber next(){
  current = current + 2
  return new EvenNumber(current)
 }
 
 EvenNumber previous(){
  current = current - 2
  return new EvenNumber(current)
 }
 
 int compareTo(EvenNumber other){
  return this.num <=> other.num
 }
 
 String toString(){
  return num + ""
 }
}

EvenNumber first = new EvenNumber(10)
EvenNumber last = new EvenNumber(25)

def range = first..last

for(i in range){
 print i.toString() + " "
}

Output
10 12 14 16 18 20 22 24 26


Previous                                                 Next                                                 Home

No comments:

Post a Comment