给出以下代码:
val future = read(1234) // <-- returns Option[MyClass]
future.map { mc =>
println(mc) // <-- this is printed
mc match {
case Some(mc2) => println("class was matched")
case None => println("class is None")
case _ => println("something else")
}
}
它会打印Some(MyClass(111,222,...
,但它不会打印任何其他内容,尤其是即使选项为某些内容,它也不会打印class was matched
。为什么会这样?
答案 0 :(得分:0)
尝试使用andThen
代替map
。
val future = read(1234) // <-- returns Option[MyClass]
future.andThen { mc =>
println(mc) // <-- this is printed
mc match {
case Some(mc2) => println("class was matched")
case None => println("class is None")
case _ => println("something else")
}
}
答案 1 :(得分:0)
尝试检查onFailure
。通常当标准清晰的东西不起作用时,就意味着之前发生了错误。
答案 2 :(得分:0)
如果val
future
返回Option[Foo]
,那么模式匹配必须匹配来自Foo
的值:
case class Foo(x: Int)
val future = Option(Foo(42))
future.map {
case _: Foo => println("the class is Foo")
case _: Option[Foo] => println("option")
}
// class was matched
这将打印class was matched
。请注意,编译器会在Option
上抱怨无结果类型测试,因为我们匹配Foo
类型的某些内容。但我们可以在Foo.x
future.map {
case Foo(32) => "nope"
case Foo(42) => "yep"
case _ => "something else"
}
Some("yep")
如果名称所暗示的future
具有类型Future[Option[Foo]]
,那么匹配是正确的,它应该打印正确的值
val future2 = Future {
Option(Foo(42))
}
future2.map {
case Some(_) => println("some")
case None => println("none")
case _ => println("wat")
}
// some