2015年12月16日 星期三

[ GroovyGN ] Newify to Create New Instances

Source From Here
Introduction
The @Newify transformation annotation allows other ways to create a new instance of a class. We can use a new() method on the class or even omit the whole new keyword. The syntax is copied from other languages like Ruby and Python. If we use the @Newify annotation we get a slightly more readable piece of code (in some situations). We can use parameters in the annotation to denote all those classes we want to be instantiated with the new() method or without the new keyword.

Sample Code
  1. class Author {  
  2.     String name  
  3.     List books  
  4. }  
  5. class Book {   
  6.     String title   
  7. }  
  8.   
  9. def createKing() {  
  10.     new Author(name: 'Stephen King', books: [  
  11.         new Book(title: 'Carrie'),  
  12.         new Book(title: 'The Shining'),  
  13.         new Book(title: 'It')  
  14.     ])  
  15. }  
  16.   
  17. assert 3 == createKing().books.size()  
  18. assert 'Stephen King' == createKing().name  
  19. assert 'Carrie' == createKing().books.getAt(0).title  
  20.   
  21. @Newify([Author, Book])   
  22. def createKingRuby() {  
  23.     Author.new(name: 'Stephen King', books: [  
  24.         Book.new(title: 'Carrie'),  
  25.         Book.new(title: 'The Shining'),  
  26.         Book.new(title: 'It')  
  27.     ])  
  28. }  
  29.   
  30. assert 3 == createKingRuby().books.size()  
  31. assert 'Stephen King' == createKingRuby().name  
  32. assert 'Carrie, The Shining, It' == createKingRuby().books.title.join(', ')  
  33.   
  34. @Newify([Author, Book])   
  35. def createKingPython() {  
  36.     Author(name: 'Stephen King', books: [  
  37.         Book(title: 'Carrie'),  
  38.         Book(title: 'The Shining'),  
  39.         Book(title: 'It')  
  40.     ])  
  41. }  
  42.   
  43. assert 3 == createKingPython().books.size()  
  44. assert 'Stephen King' == createKingPython().name  
  45. assert 'It' == createKingPython().books.title.find { it == 'It' }  


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...