Reputation: 6039
Suppose I have MyCoolClass
which accepts a type parameter T
.
Depending on T
we want to define aFun
in this way:
If (
T
is the same type asB
)aFun
should be set to() => new B
else If (
T
is the same type asC
)aFun
should be set to() => new C
otherwise show an error.
class MyCoolClass[T]{
def aFun = ... // fill this part
}
class A {
// something here
}
class B extends A {
// something more here
}
class C extends A {
// yet more things here
}
How would you go about doing this?
Upvotes: 0
Views: 24
Reputation: 12783
You can't do that this way. What you can do is instead restrict T
s in MyCoolClass to require a instance of a type class that would know how to instantiate T
:
trait Cons[T] { def cons:T }
class MyCoolClass[T](implicit ev:Cons[T]) {
def aFun = ev.cons
}
Now what we need is define A
and B
and Cons[A]
and Cons[B]
(**)
class A
class B
object A { implicit def consA:Cons[A] = new Cons[A] { def cons = new A } }
object B { implicit def consA:Cons[B] = new Cons[B] { def cons = new B } }
Now in the REPL:
scala> new MyCoolClass[A].aFun
res0: A = A@1521d074
scala> new MyCoolClass[B].aFun
res1: B = B@19cdb1cb
(**) If you happen to try that in the REPL remember to copy and paste it in a :paste command, otherwise object A and B won't really be companion objects and this own't work
Upvotes: 2