【问题标题】:Scala: avoiding cast to type parameter in foldLeftScala:避免强制转换为 foldLeft 中的类型参数
【发布时间】: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 )

有没有办法避免这种显式转换,或者更一般地说,以更好的方式实现预期结果?谢谢。

【问题讨论】:

    标签: scala casting fold


    【解决方案1】:

    需要添加自类型注解,确保StateThis

    trait State[+This <: State[This]] { this: This =>
      def update: This  // result has type of State's implementor
    }
    

    在没有折叠的情况下重新定义 update(Int) 方法的可能方法是:

    def update(steps: Int): This = Iterator.iterate(this)(_.update).drop(steps).next
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-30
      • 1970-01-01
      • 2014-10-09
      • 1970-01-01
      相关资源
      最近更新 更多