我对我不理解的类型有疑问。在下面的代码中,我有两个方法half1
,half2
它们完全相同,除了half1
显式指定的返回类型。然而,当我在 foldLeft 中使用这两种方法时half
会导致编译器错误。这是代码。设置的线路val c
有问题。
package org.bodhi.reactive.`try`
import scala.util.{Try, Success, Failure}
object Hello {
def main(args: Array[String]): Unit = {
val list = List(1,2,3)
Try(1024).flatMap(half1)
Try(1024).flatMap(half2)
half1(1024).flatMap(half1)
half2(1024).flatMap(half2)
val a = list.foldLeft(Try(1024))((accum, n) => accum.flatMap(half1))
val b = list.foldLeft(half1(1024))((accum, n) => accum.flatMap(half1))
val c = list.foldLeft(half2(1024))((accum, n) => accum.flatMap(half2)) // Compiler error
}
def half1(n: Int): Try[Int] =
if (n % 2 == 0) Success(n / 2)
else Failure(new Exception(s"WRONG $n"))
def half2(n: Int) =
if (n % 2 == 0) Success(n / 2)
else Failure(new Exception(s"WRONG $n"))
}
我得到的错误是:
[error] /home/chris/projects/reactive/example/src/main/scala/org/bodhi/reactive/try/Hello.scala:18: type mismatch;
[error] found : scala.util.Try[Int]
[error] required: Product with Serializable with scala.util.Try[Int]
[error] val c = list.foldLeft(half2(1024))((accum, n) => accum.flatMap(half2))
我的问题是:为什么会half1
在 foldLeft 中出现,但half2
没有?我正在使用 Scala 2.11.5