【发布时间】:2015-10-20 17:51:13
【问题描述】:
我有一个接受类型参数的类,我希望该类上的方法仅限于遵循该参数化的参数。但是,当类被具体实例化时,类型参数混合了其他特征,我想忽略该方法。具体来说:
trait X {def str = "X"}
trait X1 extends X {def str = "X1"}
trait X2 extends X {def str = "X1"}
trait Y
class Foo[A <: X] { def do(a:A) = a.str}
val f = new Foo[X1 with Y]
val x1 = new X1 {}
val x2 = new X2 {}
val y = new Y {}
// I want this to compile
f.do(x1)
// and these to not compile
f.do(x2)
f.do(y)
目前三个 final 语句都没有编译,但我想在 Foo.do 方法上设置类型参数,以便只编译第一个语句。但是,我不知道如何从声明中“提取”A 类型的适当部分。
【问题讨论】:
-
我认为没有这样的工具可以拆分复合类型。
-
我不认为你能得到的最接近的可能是 (imo)
class Foo[A <: X] { def func[B >: A <: X ](b:B) = b.str }仍然包括f.do(x2)
标签: scala types type-parameter