Scala 例如,产生类型不匹配的编译器错误
我想从Iterable[Try[Int]]中提取所有有效值的列表Iterable[Int] 以下是打印测试中所有有效值的方法: 但是,当我试图将有效值保存到列表时,我收到一个错误:Scala 例如,产生类型不匹配的编译器错误,scala,compiler-errors,yield,type-mismatch,for-comprehension,Scala,Compiler Errors,Yield,Type Mismatch,For Comprehension,我想从Iterable[Try[Int]]中提取所有有效值的列表Iterable[Int] 以下是打印测试中所有有效值的方法: 但是,当我试图将有效值保存到列表时,我收到一个错误: val nums: Seq[Int] = for { n <- list p <- n // Type mismatch. Required: IterableOnce[Int], found Try[Int] } yield(p) println(nums) 如何修复错误以及引发
val nums: Seq[Int] = for {
n <- list
p <- n // Type mismatch. Required: IterableOnce[Int], found Try[Int]
} yield(p)
println(nums)
如何修复错误以及引发错误的原因?请尝试收集
test.collect { case Success(value) => value }
// res0: List[Int] = List(8, 42)
以对应于
for { Success(p) <- test } yield p
下面的理解方法不起作用,因为其中的单子必须对齐
for {
n <- test // List monad
p <- n // does not align with Try monad
} yield (p)
看看flatMap的签名,我们看到它需要一个函数
Try[Int] => IterableOnce[Int]
当我们提供
Try[Int] => Try[Int]
因为n.mapp:Int=>p返回Try[Int]。下面的理解是一个完全不同的野兽
for {
n <- test
p <- n
} println(p)
其中foreach需要类型为的函数
Try[Int] => Unit
我们确实提供了它,因为n.foreachp:Int=>printlnp确实返回单位。尝试收集
test.collect { case Success(value) => value }
// res0: List[Int] = List(8, 42)
以对应于
for { Success(p) <- test } yield p
下面的理解方法不起作用,因为其中的单子必须对齐
for {
n <- test // List monad
p <- n // does not align with Try monad
} yield (p)
看看flatMap的签名,我们看到它需要一个函数
Try[Int] => IterableOnce[Int]
当我们提供
Try[Int] => Try[Int]
因为n.mapp:Int=>p返回Try[Int]。下面的理解是一个完全不同的野兽
for {
n <- test
p <- n
} println(p)
其中foreach需要类型为的函数
Try[Int] => Unit
我们确实提供了它,因为n.foreachp:Int=>printlnp确实返回单位。您也可以尝试:
val nums: Seq[Int] = list.map(_.toOption).flatten
或
您也可以尝试:
val nums: Seq[Int] = list.map(_.toOption).flatten
或