Pastebin launched a little side project called HostCabi.net, check it out ;-)Don't like ads? PRO users don't see any ads ;-)
Guest

Scala Immutable Builder with tight guided fluent interface

By: a guest on Aug 26th, 2010  |  syntax: Scala  |  size: 1.69 KB  |  hits: 100  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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. }