【发布时间】:2011-12-05 18:45:55
【问题描述】:
考虑一下这个 sn-p 定义了模拟状态的特征,用户希望在某些派生类型中实现该特征。在 trait 上,实用方法的集合应该能够提供具有实现类型的结果,类似于 Scala 库集合执行此操作的方式。为此,我认为我需要使用实现类型参数化特征,如下所示:
trait State[+This <: State[This]] {
def update : This // result has type of State's implementor
}
现在我想定义一个多步更新方法,像这样:
def update(steps: Int) : This
当我尝试天真的方法时:
def update(steps: Int) : This =
(this /: (0 until steps))( (s,n) => s.update )
编译器抱怨类型不匹配:
error: type mismatch;
found: State[This]
required: This
这是有道理的,因为在 State 中看到的 this 具有 State[This] 类型。
要编译代码,似乎我必须进行显式转换:
def update(steps: Int) : This =
(this.asInstanceOf[This] /: (0 until steps))( (s,n) => s.update )
有没有办法避免这种显式转换,或者更一般地说,以更好的方式实现预期结果?谢谢。
【问题讨论】: