Note that there are some explanatory texts on larger screens.

plurals
  1. POSuccess/failure chain pattern in Scala
    primarykey
    data
    text
    <p>I have a workflow like this:</p> <pre><code>parse template -&gt; check consistency -&gt; check conformance of one template to another parse template -&gt; check consistency </code></pre> <p>Either one of those steps may fail. I would like to implement that in Scala, preferably so that the parallel branches get evaluated independently merging both their errors. Perhaps in a monadic style but I am curious about some general OOP pattern too. Currently I have multiple variations hardcoded for various actions with the chaining like this</p> <pre><code>def loadLeftTemplateAndForth (leftPath : String, rightPath : String) = { val (template, errors) = loadTemplate(leftPath) if(errors.isEmpty) loadRightTemplateAndForth(template, rightPath) else popupMessage("Error.") } </code></pre> <p>which I bet must be some kind of antipattern. The steps need decoupling from the workflow but I was not able to come up with anything extremely elegant and there must proven ways already.</p> <p><strong>EDIT:</strong> Ok, so I have unsuccessfully tried to implement something like this</p> <pre><code>(((parseTemplate(path1) :: HNil).apply(checkConsistency _) :: ((parseTemplate(path2) :: HNil).apply(checkConsistency _)) :: HNil).apply(checkConformance _) def checkConformance (t1 : Template)(t2 : Template) : Seq[Error] </code></pre> <p>The functions would then return Success(result) or Failure(errors). I was using HLists but got lost in the type inference rules and other issues. It seems I was pretty close though. For someone knowledgable of this stuff it would probably be a piece of cake.</p> <p><strong>EDIT:</strong> I have finally managed to implement this</p> <pre><code>(parseTemplate("Suc") :: Args).apply(checkConsistency _) :: (parseTemplate("Suc") :: Args).apply(checkConsistency _) :: Args) .apply(checkConformance _) </code></pre> <p>with some unfornate constraints that each function must return my equivalent of Either and that the error type of applied function must be a subtype of arguments' error type. I did it using HList, application typeclass and a wrapper class Successful/UnsuccessfulArgList.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload