是否有现有的组合器或更好的写入方式?
def combine[I, A](k: Kleisli[Try, I, A], default: A) : I => A =
k.run.andThen(_.getOrElse(default))
答案 0 :(得分:0)
可以使用Identity:
对monadic值进行映射def combine[I, A](k: Kleisli[Try, I, A], default: A): I => A =
k.mapF[Id, A](_.getOrElse(default)).run
示例:
scala> val div = Kleisli[Try, Int, String](x => Try(1000 / x).map(_.toString))
div: cats.data.Kleisli[scala.util.Try,Int,String] = Kleisli(<function1>)
scala> combine(div, "Good")(10)
res0: String = 100
scala> combine(div, "Division by zero")(0)
res1: String = Division by zero