繁体   English   中英

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

[英]Scala bound on part of a 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 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)

当前,这三个最终语句都不编译,但是我想在Foo.do方法上设置type参数,以便仅第一个语句编译。 但是,我不知道如何从声明中“提取” 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)

也就是说,这种方法在几种方面仍然不是最优的,即我们需要在编译时知道在运行时可能混入A所有类型。 另外,还需要仔细管理隐式函数的范围,以确保其不会泄漏到可能引起问题的情况中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM