Advertisement
Guest User

Scala Immutable Builder with tight guided fluent interface

a guest
Aug 26th, 2010
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.69 KB | None | 0 0
  1. /**
  2.  * Example of an immutable pojo with a built-in builder.
  3.  * Still pretty ugly translation of java version at http://pastebin.com/zt8vE8Fw
  4.  * @author twitter.com/benhardy
  5.  */
  6. class PersonFeatures2(val userId:Int, val age:Int, val children:Int, val dogs:Int) {
  7.  
  8. }
  9.  
  10. object PersonFeatures2 {
  11.     // give each stage of the builder only one callable method,
  12.     // which returns the next stage
  13.  
  14.     trait BuilderUserIdSpec {
  15.         def userId(v:Int): BuilderAgeSpec
  16.     }
  17.     trait BuilderAgeSpec {
  18.         def age(v:Int) : BuilderChildrenSpec
  19.     }
  20.     trait BuilderChildrenSpec {
  21.         def  children(v:Int) : BuilderDogsSpec
  22.     }
  23.     trait BuilderDogsSpec {
  24.         def  dogs(v:Int): BuilderFinal
  25.     }
  26.     trait BuilderFinal {
  27.         def  build : PersonFeatures2
  28.     }
  29.  
  30.  
  31.     def builder = {
  32.       new BuilderUserIdSpec() {
  33.         override def userId(_userId:Int) = {
  34.           new BuilderAgeSpec() {
  35.             override def age(_age:Int) = {
  36.               new BuilderChildrenSpec() {
  37.                 override def children(_children:Int) = {
  38.                   new BuilderDogsSpec() {
  39.                     override def dogs(_dogs:Int) = {
  40.                       new BuilderFinal() {
  41.                         override def build = {
  42.                           new PersonFeatures2(_userId, _age, _children, _dogs)
  43.                         }
  44.                       }
  45.                     }
  46.                   }
  47.                 }
  48.               }
  49.             }
  50.           }
  51.         }
  52.       }
  53.     }
  54.  
  55.     /**
  56.      * example usage. pretty obvious what is going on. only one way to do it. IDE will help.
  57.      */
  58.     val person = builder userId(4437) age(22) children(0) dogs(1) build
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement