简体   繁体   中英

Scala generics: type mismatch with folding

New to scala. Trying to understand why scala compiler is not happy about the below:

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?

Please help.

For a general A , usual "addition" is not defined. So instead, it implicitly converts A into String , and uses the + that concatenates String s. 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 somewhat more systematic approach would be to use Numeric typeclass, just like the method in the standard library (unfold "use case" and "Full signature").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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