2015年12月16日 星期三

[ GroovyGN ] Define Your Own Type Conversion

Source From Here 
Introduction 
In Groovy we can override the method asType() to convert an object into another type. We can use the method asType() in our code to invoke the conversion (Check DefaultGroovyMethods), but we can even make it shorter an useas

Sample Code 
  1. class Size {  
  2.     def x, y  
  3.       
  4.     Object asType(Class clazz) {  
  5.         if (clazz == SquaredSize) {  
  6.             new SquaredSize(x: x**2, y: y**2)  
  7.         }  
  8.     }  
  9. }  
  10.   
  11. class SquaredSize {  
  12.     def x, y  
  13.       
  14.     String toString() { "x: $x, y: $y" }  
  15. }  
  16.   
  17. def size = new Size(x: 10, y: 5)  
  18. def squared = size as SquaredSize  // Or size.asType(SquaredSize)  
  19.   
  20. println squared  // Output: x: 100, y: 25  
  21.   
  22. assert 100 == squared.x  
  23. assert 25 == squared.y  

沒有留言:

張貼留言

[Linux 常見問題] sudo: Sorry, you must have a tty to run sudo Error on a Linux and Unix

Source From  Here   Preface   I‘m trying to run the following command:  #   ssh  user@box.example.com  sudo command1 /path/to/file But, a...