Both Success and Failure extend Try[T] with Product with Serializable , ( Product with Serializable , because these are case classes). Therefore, when you leave the return type half2 , the return type is displayed as Try[T] with Product with Serializable .
Usually it doesnβt matter, flatMap(half2) will still return Try[T]
scala> Try(1024).flatMap(half2) res2: scala.util.Try[Int] = Success(512)
But foldLeft is a completely different story. The problem is that you are passing half(2) as the first argument. Take a look at the signature foldLeft :
def foldLeft[B](z: B)(op: (A, B) => B): B
B is inferred from the argument z , which means
B = Try[T] with Product with Serializable
This means that op expected to be of type:
(A, Try[T] with Product with Serializable) => Try[T] with Product with Serializable
But instead, it is (A, Try[T]) => Try[T] , and this way you get a type mismatch. Using type inference can be nice, but most of the time I explicitly type in return types, you will save a lot of headaches.
source share