Created
June 10, 2014 16:29
-
-
Save gclaramunt/1a9be9846146b8778e67 to your computer and use it in GitHub Desktop.
Attempt to a typesafe factory patter in scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by claramun on 6/9/14. | |
*/ | |
trait A | |
trait B { val value:String } | |
trait X1A extends A | |
trait X1B extends B | |
trait X2A extends A | |
trait X2B extends B | |
trait X{ | |
type A1 <: A | |
type B1 <: B | |
val in:A1 | |
def xx(a:A1):B1 | |
} | |
object X1 extends X{ | |
type A1 = X1A | |
type B1 = X1B | |
val in = new X1A {} | |
def xx(a:A1):B1 = { | |
new X1B{ val value = "X1B ="+a } | |
} | |
} | |
object X2 extends X{ | |
type A1 = X2A | |
type B1 = X2B | |
val in = new X2A {} | |
def xx(a:A1):B1 = { | |
new X2B{ val value = "X2B ="+a } | |
} | |
} | |
object Factory { | |
def build(x:Any):X= x match { | |
case i:Int => X1 | |
case s:String => X2 | |
} | |
} | |
object Run extends App { | |
val x1=Factory.build(1) | |
val x2= Factory.build("a") | |
println("1 "+x1.xx(x1.in).value) | |
println("a "+x2.xx(x2.in).value) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment