简体   繁体   English

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

[英]Scala bound on part of a type parameter

I have a class that takes a type parameter and I'd like a method on the class to be restricted to arguments that adhere to that parameterization. 我有一个带有类型参数的类,我希望该类上的方法仅限于遵循该参数化参数的参数。 However when the class is concretely instantiated the type parameter has additional traits mixed in that I'd like to ignore for the method. 但是,当具体实例化该类时,类型参数具有其他特征,我想忽略该方法的其他特征。 Concretely: 具体来说:

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)

Currently none of the three final statements compile, but I'd like to set the type parameter on the Foo.do method such that only the first statement compiles. 当前,这三个最终语句都不编译,但是我想在Foo.do方法上设置type参数,以便仅第一个语句编译。 I don't know how to 'extract' the appropriate part of the type of A from the declaration however. 但是,我不知道如何从声明中“提取” A类型的适当部分。

I've hit upon a solution, though it is not too elegant and I'm open to other ones. 我已经找到了一个解决方案,尽管它不是太优雅,而且我愿意接受其他解决方案。 Since, by supposition, I am only going to use methods on X in my do method (as they are the only ones visible to the type) I can cast the input argument to the appropriate type using an implicit as follows: 因为假设,我只打算在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)

That said, this approach is still suboptimal in several ways, namely we need to know at compile time all of the types that might be mixed in to A at runtime. 也就是说,这种方法在几种方面仍然不是最优的,即我们需要在编译时知道在运行时可能混入A所有类型。 Also the scope of the implicit needs to be carefully managed to ensure that it does not leak out into a situation where it could cause problems. 另外,还需要仔细管理隐式函数的范围,以确保其不会泄漏到可能引起问题的情况中。

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

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