Chaining PartialFunctions with andThen in Scala

前端 未结 3 1297
暗喜
暗喜 2020-12-20 12:56

Let us reuse examples from Daily scala :

type PF = PartialFunction[Int,Int]

val pf1 : PF = {case 1 => 2}                      

val pf2 : PF = {case 2 =&         


        
3条回答
  •  佛祖请我去吃肉
    2020-12-20 13:31

    You need the equivalent of flatMap for PartialFunctions.

    implicit class CollectPartial[A, B](f: PartialFunction[A, B]) {
        def collect[C](g: PartialFunction[B, C]) = Function.unlift { a: A =>
            f.lift(a).flatMap(g.lift)
        }
    }
    

    Use it like

    val a: PartialFunction[String, Int] = ...
    val b: PartialFunction[Int, Char] = ...
    val c: PartialFunction[String, Char] = a collect b
    

    This works as expected even with side-effects.

提交回复
热议问题