Transactional effect in Scala

Ivan Kurchenko
1 min readJan 24, 2021

--

Introduction

This blogpost inspired by StackOverflow answer for question: Compose Futures with Recovery in Scala: is it possible to compose Future's in a manner if one of them will fail, previous Future's execution result will be
rolled back via some function.

The problem

Case with Future can be generalized to some effect F[_], so we can say: How we can compose effects F[_] in a manner if one of them will fail, previous F[_] execution result will be rolled back via some function. This behaviour similar to what we know as Transaction.

Solution

For code solution below cats-effect version `2.3.1` used. Final solution with a small demo can look like:

Which will print out next output (shorter for sake of example):

A executed
B executed
B recovered
A recovered
java.lang.Exception: C failed

Also you can play with demo in Scatie: https://scastie.scala-lang.org/W8qmBrVQRx6izAVo3Q9yvg

Thank you for attention and hope it will be helpfull.

--

--