繁体   English   中英

Scala泛型:类型与折叠不匹配

[英]Scala generics: type mismatch with folding

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?

请帮忙。

对于一般A ,通常的“添加”没有定义。 因此,它隐式地将A转换为String ,并使用连接String+ 一个快速而肮脏的解决方法是:

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

只有当AInt才会使sum可用。 一种更为系统化的方法是使用Numeric类型类,就像标准库中的方法一样(展开“用例”和“完全签名”)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM