Anlamadığım türlerle ilgili bir sorunum var. Aşağıdaki kodda half1
ve half2
iki yöntem var, half1
dönüş türü açıkça belirtilmedikçe aynıdır. Yine de bir katlamada half
iki yöntemi kullandığımda bir derleyici hatasına neden olur. İşte kod. val c
'u ayarlayan satırda sorun var.Scala tipi hatası ile deneyin [Int]
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"))
}
alıyorum hatadır:
[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))
Sorum şu: foldLeft içinde half1
comile yapar, ama neden half2
yok ki? I (onlar vaka sınıfları çünkü Product with Serializable
) Try[T] with Product with Serializable
uzatmak