尝试使用
scalaz.Need
.
https://static.javadoc.io/org.scalaz/scalaz_2.12/7.2.26/scalaz/Need.html
case class Foo(bar: String, baz: Option[String])
def expensiveOperation1(): String = {
println("operation1")
"Value3"
}
def expensiveOperation2(): List[Int] = {
println("operation2")
List(1, 2, 3)
}
def expensiveOperation3(): Foo = {
println("operation3")
Foo("x", Some("x"))
}
lazy val r1 = Need(expensiveOperation1())
lazy val r2 = Need(expensiveOperation2())
lazy val r3 = Need(expensiveOperation3())
(r1, r2, r3) match {
case (Need("Value1"), _, _) => "1"
case (Need("Value2"), _, _) => "2"
case (_, Need(List(1)), _) => "3"
case (_, Need(Nil), _) => "4"
case (Need("Value3"), Need(1 :: tail), _) => "5" + tail
case (_, _, Need(Foo("x", Some(x)))) => x
case (_, _, _) => "7"
}
operation1
operation2