Scala泛型:折叠类型不匹配

时间:2019-02-12 04:18:45

标签: scala generics

scala的新手。试图了解为什么Scala编译器对以下内容不满意:

sealed trait LinkedList[A] {
  def fold[B](end: B)(func: (A, B) => B): B =
    this match {
      case End() => end
      case Pair(hd, tl) => func(hd, tl.fold(end)(func))
    }

  def sum: Int =
    fold[Int](0){(hd, tl) => hd + tl}
}

final case class Pair[A](head: A, tail: LinkedList[A]) extends LinkedList[A]
final case class End[A]() extends LinkedList[A]

object Foo extends App {
  val example = Pair(1, Pair(2, Pair(3, End())))
  println(example.sum)
}

出现此错误:

Error:(10, 35) type mismatch;
 found   : Int
 required: String
    fold[Int](0){(hd, tl) => hd + tl}

如何在这里推断String?

请帮助。

1 个答案:

答案 0 :(得分:3)

对于常规A,未定义常规的“添加”。因此,它会将A隐式转换为String,并使用连接+的{​​{1}}。一个快速而肮脏的解决方法是:

String

仅当def sum(implicit i: A =:= Int): Int = fold[Int](0){(hd, tl) => i(hd) + tl} sum时,A才可用。更加系统化的方法是使用Int类型类,就像standard library中的方法一样(展开“用例”和“完整签名”)。

相关问题