【问题标题】:Generic Programming in ScalaScala 中的泛型编程
【发布时间】:2013-10-08 21:26:41
【问题描述】:

大家好,我是来自 C# 的 Scala 新手。

我正在尝试编写我自己的累积(折叠)版本我想知道为什么我会遇到以下问题:

def accumulate[T](list : List[T], initial: T, f: (T, T) => T) : T = {
    @tailrec def loop[T](list: List[T], accum: T) : T =
      if(list.length == 0)
        accum
      else{
        val head : T = list.head
        val res : T = f(accum,head)
        loop[T](list.tail, res)
      }
    loop(list,initial)
  }

我收到以下错误:

type mismatch;
 found   : accum.type (with underlying type T)
 required: T
        val res : T = f(accum,head)
                        ^

考虑到一切都是 T 类型,我看不出我是如何出现类型不匹配的。

任何想法/帮助将不胜感激。

布莱尔

【问题讨论】:

    标签: scala generics generic-programming


    【解决方案1】:

    您应该从loop 方法中删除类型参数。将loop[T] 替换为loop

    使用loop[T],您正在创建名称为T 的新类型参数,因此loop 方法之外的Tloop 方法中的T 是具有相同名称的不同类型别名。

    这叫做阴影

    查看类似问题的答案:

    1. Scala type parameter error, not a member of type parameter
    2. Scala, Extend object with a generic trait
    3. Generic type inference in Scala

    【讨论】:

    • 啊,现在这么明显了 :) 谢谢
    【解决方案2】:

    问题在于,使用内部函数loop,您正在定义一个新类型T,它隐藏了外部类型T

    编译器将它们视为定义不同的类型。如果您只是从loop 中删除T 类型参数(包括递归调用loop(list.tail, res)),您应该会发现它编译得很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-05
      • 2018-01-01
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 2014-02-09
      • 1970-01-01
      相关资源
      最近更新 更多