Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active February 3, 2026 20:20
Show Gist options
  • Select an option

  • Save dacr/dd25453d53fb97da0cef816b6f8791e5 to your computer and use it in GitHub Desktop.

Select an option

Save dacr/dd25453d53fb97da0cef816b6f8791e5 to your computer and use it in GitHub Desktop.
ZIO learning - transactions / published by https://github.com/dacr/code-examples-manager #382b643a-6998-4726-82e5-9d8080f5ac26/ff12d1298fcdc36ae0ff723d450e991db0f37e5e
// summary : ZIO learning - transactions
// keywords : scala, zio, learning, pure-functional, transactions, @testable
// publish : gist
// authors : David Crosson
// license : Apache License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
// id : 382b643a-6998-4726-82e5-9d8080f5ac26
// created-on : 2021-11-06T08:14:16Z
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.4.2"
//> using dep "dev.zio::zio:2.0.13"
// ---------------------
/*
inspired from https://zio.dev/datatypes/stm/stm
*/
import zio.*
import zio.stm.*
import java.io.IOException
object Encapsulated extends ZIOAppDefault {
def transferMoney(from: TRef[Long], to: TRef[Long], amount: Long): STM[String, (Long, Long)] =
for {
senderBalance <- from.get
_ <- if (senderBalance < amount) STM.fail("Not enough money") else STM.unit
_ <- from.update(existing => existing - amount)
_ <- to.update(existing => existing + amount)
senderBalance <- from.get
receiverBalance <- to.get
} yield (senderBalance, receiverBalance)
val app: ZIO[Any, IOException | String, (Long, Long)] = for {
senderAccount <- STM.atomically(TRef.make(1000L))
receiverAccount <- STM.atomically(TRef.make(0L))
result <- STM.atomically(transferMoney(senderAccount, receiverAccount, 420L))
_ <- Console.printLine(result)
} yield result
def run = app
}
Encapsulated.main(Array.empty)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment