相关疑难解决方法(0)

for-comprehension yield 引发类型不匹配编译器错误

我想从Iterable[Try[Int]]所有有效值的列表中提取( Iterable[Int])

val test = List(
    Try(8), 
    Try(throw new RuntimeException("foo")), 
    Try(42), 
    Try(throw new RuntimeException("bar"))
)
Run Code Online (Sandbox Code Playgroud)

以下是从 打印所有有效值的方法test

for {
    n <- test
    p <- n
} println(p)

// Output
// 8
// 42
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试将有效值保存到列表时,我收到了一个错误:

val nums: Seq[Int] = for {
    n <- list
    p <- n    // Type mismatch. Required: IterableOnce[Int], found Try[Int]
} yield(p)
println(nums)
Run Code Online (Sandbox Code Playgroud)

如何修复错误以及它为什么被提出?

scala yield compiler-errors type-mismatch for-comprehension

1
推荐指数
1
解决办法
93
查看次数