[英]Scala generics: type mismatch with folding
New to scala. scala新手。 Trying to understand why scala compiler is not happy about the below:
试图理解为什么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)
}
Getting this error: 得到此错误:
Error:(10, 35) type mismatch;
found : Int
required: String
fold[Int](0){(hd, tl) => hd + tl}
How is String being inferred here? 如何在这里推断出String?
Please help. 请帮忙。
For a general A
, usual "addition" is not defined. 对于一般
A
,通常的“添加”没有定义。 So instead, it implicitly converts A
into String
, and uses the +
that concatenates String
s. 因此,它隐式地将
A
转换为String
,并使用连接String
的+
。 A quick and dirty workaround would be: 一个快速而肮脏的解决方法是:
def sum(implicit i: A =:= Int): Int = fold[Int](0){(hd, tl) => i(hd) + tl}
This would make sum
available only if A
is Int
. 只有当
A
是Int
才会使sum
可用。 A somewhat more systematic approach would be to use Numeric
typeclass, just like the method in the standard library (unfold "use case" and "Full signature"). 一种更为系统化的方法是使用
Numeric
类型类,就像标准库中的方法一样(展开“用例”和“完全签名”)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.