访问类型参数的类型参数
我想在一个特征中访问该特征的类型参数的类型参数。无需将此“二阶”类型参数作为另一个“一阶”参数添加到特征中。下面说明了这个问题:
sealed trait A; sealed trait A1 extends A; sealed trait A2 extends A
trait B[ ASpecific <: A ] { type ASpec = ASpecific }
trait D[ ASpecific <: A ] extends B[ ASpecific ]
trait C[ +BSpecific <: B[ _ <: A ]] {
def unaryOp : C[ D[ BSpecific#ASpec ]]
}
def test( c: C[ B[ A1 ]]) : C[ D[ A1 ]] = c.unaryOp
测试无法编译,因为显然 c.unaryOp 的结果类型为 C[D[A]] 而不是 C[D[A1]],表明 ASpec 只是 _ < 的快捷方式;:A 并不指具体的类型参数。
双类型参数解决方案很简单:
sealed trait A; sealed trait A1 extends A; sealed trait A2 extends A
trait B[ ASpecific <: A ]
trait D[ ASpecific <: A ] extends B[ ASpecific ]
trait C[ ASpecific <: A, +BSpecific <: B[ ASpecific ]] {
def unaryOp : C[ ASpecific, D[ ASpecific ]]
}
def test( c: C[ A1, B[ A1 ]]) : C[ A1, D[ A1 ]] = c.unaryOp
但我不明白为什么我需要用第二个明显多余的参数来混乱我的源代码。有没有办法从特征B中检索它?
i would like to access, in a trait, the type-parameter of a type-parameter of that trait. without adding this "second-order" type-parameter as another "first-order" parameter to the trait. the following illustrates this problem:
sealed trait A; sealed trait A1 extends A; sealed trait A2 extends A
trait B[ ASpecific <: A ] { type ASpec = ASpecific }
trait D[ ASpecific <: A ] extends B[ ASpecific ]
trait C[ +BSpecific <: B[ _ <: A ]] {
def unaryOp : C[ D[ BSpecific#ASpec ]]
}
def test( c: C[ B[ A1 ]]) : C[ D[ A1 ]] = c.unaryOp
the test fails to compile because apparently, the c.unaryOp has a result of type C[D[A]] and not C[D[A1]], indicating that ASpec is merely a shortcut for _ <: A and does not refer to the specific type parameter.
the two-type-parameter solution is simple:
sealed trait A; sealed trait A1 extends A; sealed trait A2 extends A
trait B[ ASpecific <: A ]
trait D[ ASpecific <: A ] extends B[ ASpecific ]
trait C[ ASpecific <: A, +BSpecific <: B[ ASpecific ]] {
def unaryOp : C[ ASpecific, D[ ASpecific ]]
}
def test( c: C[ A1, B[ A1 ]]) : C[ A1, D[ A1 ]] = c.unaryOp
but i don't understand why i need to clutter my source with this second, obviously redundant, parameter. is there no way to retrieve it from trait B?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我可以通过在 C 中添加类型别名来使其编译:
另一个增强版本的测试:
希望它没有改变您的意图。
I could make it compile by adding a type alias in
C
:Another enhanced version of test:
Hope it haven't changed your intention.
@pedrofurla(抱歉,我在未登录的情况下无法直接回复)
虽然您的示例可以编译,但我认为您除了
C[D[A]]
之外什么也没有得到,因为正是X#BSpec
是_ <: A
的别名...@pedrofurla (sorry can't reply directly as i asked without being logged in)
although your example compiles, i think you are not getting anything from that but
C[D[A]]
because preciselyX#BSpec
being an alias for_ <: A
...