Why type declarations are required in this implementation of Scala foldLeft

I tried to implement foldLeft on LinkedList with this code, one curried foldLeft2 and the other not, foldLeft:

sealed trait LinkedList[+E] {
  @tailrec
  final def foldLeft[A](accumulator: A, f: (A, E) => A): A = {
    this match {
      case Node(h, t) => {
        val current = f(accumulator, h)
        t.foldLeft(current, f)
      }
      case Empty => accumulator
    }
  }
  @tailrec
  final def foldLeft2[A](accumulator: A)(f: (A, E) => A): A = {
    this match {
      case Node(h, t) => {
        val current = f(accumulator, h)
        t.foldLeft2(current)(f)
      }
      case Empty => accumulator
    }
  }
}

But when I use foldLeft, it seems I need to declare a type for the battery and the element, but for foldLeft2 I do not. Can someone explain why this is?

class LinkedListSpecification extends Specification {
  "linked list" should {
    "foldLeft correctly" in {
      val original = LinkedList(1,2,3,4)
      original.foldLeft(0, (acc: Int, item: Int) => acc + item) === 10
    }
  }
  "linked list" should {
    "foldLeft2 correctly" in {
      val original = LinkedList(1,2,3,4)
      original.foldLeft2(0)((acc, item) => acc + item) === 10
    }
  }
}
+4
source share
1 answer

, Scala .
, foldLeft2 A Int, , (Int,E)=>Int. foldLeft A (accumulator f). , , A.

+2

Source: https://habr.com/ru/post/1611535/


All Articles