Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Example of an immutable pojo with a built-in builder.
- * Still pretty ugly translation of java version at http://pastebin.com/zt8vE8Fw
- * @author twitter.com/benhardy
- */
- class PersonFeatures2(val userId:Int, val age:Int, val children:Int, val dogs:Int) {
- }
- object PersonFeatures2 {
- // give each stage of the builder only one callable method,
- // which returns the next stage
- trait BuilderUserIdSpec {
- def userId(v:Int): BuilderAgeSpec
- }
- trait BuilderAgeSpec {
- def age(v:Int) : BuilderChildrenSpec
- }
- trait BuilderChildrenSpec {
- def children(v:Int) : BuilderDogsSpec
- }
- trait BuilderDogsSpec {
- def dogs(v:Int): BuilderFinal
- }
- trait BuilderFinal {
- def build : PersonFeatures2
- }
- def builder = {
- new BuilderUserIdSpec() {
- override def userId(_userId:Int) = {
- new BuilderAgeSpec() {
- override def age(_age:Int) = {
- new BuilderChildrenSpec() {
- override def children(_children:Int) = {
- new BuilderDogsSpec() {
- override def dogs(_dogs:Int) = {
- new BuilderFinal() {
- override def build = {
- new PersonFeatures2(_userId, _age, _children, _dogs)
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
- /**
- * example usage. pretty obvious what is going on. only one way to do it. IDE will help.
- */
- val person = builder userId(4437) age(22) children(0) dogs(1) build
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement