[英]Conditioning on type parameters passed to a class
Suppose I have MyCoolClass
which accepts a type parameter T
. 假设我有MyCoolClass
,它接受类型参数T
Depending on T
we want to define aFun
in this way: 取决于T
我们想要以这种方式定义aFun
:
If (
T
is the same type asB
)aFun
should be set to() => new B
如果(T
与B
是同一类型)aFun
应该设置为() => new B
else If (
T
is the same type asC
)aFun
should be set to() => new C
否则如果(T
与C
类型相同)aFun
应该设置为() => 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? 您将如何去做?
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
: 您可以做的是改为限制MyCoolClass中的T
,使其要求一个类型类的实例,该实例知道如何实例化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]
(**) 现在我们需要定义A
和B
以及Cons[A]
和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: 现在在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 (**)如果您碰巧在REPL中尝试将其复制并粘贴到:paste命令中,否则对象A和B不会真正成为伴侣对象,并且此对象不起作用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.