是否有详细的指南从filter()移动到withFilter()?现在我收到有关使用filter()实现的警告,但找不到移动到withFilter()的简单指南...
for {
a <- Some(1)
b <- Some(2)
} yield (a, b)
Run Code Online (Sandbox Code Playgroud)
回报 Some((1, 2))
for {
a <- Right(1).right
b <- Left(2).left
} yield (a, b)
Run Code Online (Sandbox Code Playgroud)
回报 Left((1, 2))
现在我想在理解中分解元组.
for {
(a, b) <- Some((1, 2))
(c, d) <- Some((3, 4))
} yield (a, b, c, d)
Run Code Online (Sandbox Code Playgroud)
回报 Some((1, 2, 3, 4))
for {
(a, b) <- Right((1, 2)).right
(c, d) <- Left((3, 4)).left
} yield (a, b, c, d)
Run Code Online (Sandbox Code Playgroud)
无法编译:
error: constructor cannot be instantiated to expected …Run Code Online (Sandbox Code Playgroud) 给出以下代码snippelt:
import scala.util.Try
def foo(x:Int) : (Int, String) = {
(x+1, x.toString)
}
def main(args: Array[String]) : Unit = {
val r1: Try[(Int, String)] = for {
v <- Try { foo(3) }
} yield v
val r2: Try[(Int, String)] = for {
(i, s) <- Try { foo(3) } // compile warning refers to this line
} yield (i, s)
}
Run Code Online (Sandbox Code Playgroud)
1.为什么编译上面的代码会抛出以下警告?
`withFilter' method does not yet exist on scala.util.Try[(Int, String)], using `filter' method instead
[warn] (i, s) <- …Run Code Online (Sandbox Code Playgroud) Scala 2.10似乎更新了对Either的理解.在2.10:
scala> val a = Right(5)
a: scala.util.Right[Nothing,Int] = Right(5)
scala> for {aa: Int <- a.right} yield {aa}
<console>:9: error: type mismatch;
found : Int => Int
required: scala.util.Either[Nothing,Int] => ?
for {aa: Int <- a.right} yield {aa}
^
Run Code Online (Sandbox Code Playgroud)
在2.9.3中,以上是可以的.
scala> val a = Right(5)
a: Right[Nothing,Int] = Right(5)
scala> for {aa: Int <- a.right} yield {aa}
res0: Product with Serializable with Either[Nothing,Int] = Right(5)
Run Code Online (Sandbox Code Playgroud)
只需在2.10中删除aa的类型即可轻松修复.但我想知道为什么行为会在2.9和2.10之间发生变化.