Scala绑定在类型参数的一部分上

Scala绑定在类型参数的一部分上,scala,types,type-parameter,Scala,Types,Type Parameter,我有一个接受类型参数的类,我希望该类上的方法仅限于遵循该参数化的参数。但是,当类被具体实例化时,类型参数还混合了其他特性,我想对方法忽略这些特性。具体地说: 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 w

我有一个接受类型参数的类,我希望该类上的方法仅限于遵循该参数化的参数。但是,当类被具体实例化时,类型参数还混合了其他特性,我想对方法忽略这些特性。具体地说:

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)
trait X{def str=“X”}
特征X1扩展X{def str=“X1”}
trait X2扩展X{def str=“X1”}
性状Y

类Foo[A我想到了一个解决方案,虽然它不太优雅,而且我对其他解决方案持开放态度。因为,通过假设,我只在我的
do
方法中使用
X
上的方法(因为它们是该类型唯一可见的方法),我可以使用隐式表达式将输入参数转换为适当的类型,如下所示:

trait X {def str = "X"}
trait X1 extends X {override def str = "X1"}
trait X2 extends X {override def str = "X1"}

trait Y

trait X {def str = "X"}

implicit def x2xWy[Xt <: X](x:Xt):Xt with Y = x.asInstanceOf[Xt with Y]

class Foo[A <: X] { def doIt[A1](a:A1)(implicit toA:(A1 => A)) = toA(a).str}

// this compiles
f.doIt(x1)
// and these do not
f.doIt(x2)
f.doIt(y)
trait X{def str=“X”}
trait X1扩展X{override def str=“X1”}
trait X2扩展X{override def str=“X1”}
性状Y
特征X{def str=“X”}

隐式def x2xWy[Xt我不认为有一种工具可以拆分这样的复合类型。我不认为你能得到的最接近的可能是(imo)
class Foo[a:a]