scp2: use monad for/yield syntax

This commit is contained in:
2025-11-07 12:49:30 +01:00
parent a187ea07b4
commit 1f88d14f9d

View File

@@ -73,23 +73,15 @@ class Bank(val allowedAttempts: Integer = 3) {
private def processSingleTransaction(t: Transaction): Thread =
new Thread(() => {
accountsRegistry.synchronized {
val fromOpt = getAccount(t.from)
val toOpt = getAccount(t.to)
(fromOpt, toOpt) match {
case (Some(from), Some(to)) =>
from.withdraw(t.amount) match {
case Right(updatedFrom) =>
to.deposit(t.amount) match {
case Right(updatedTo) =>
accountsRegistry(t.from) = updatedFrom
accountsRegistry(t.to) = updatedTo
t.succeed()
case Left(_) => t.fail()
}
case Left(_) => t.fail()
}
case _ => t.fail()
for {
from <- getAccount(t.from)
to <- getAccount(t.to)
updatedFrom <- from.withdraw(t.amount).toOption
updatedTo <- to.deposit(t.amount).toOption
} yield {
accountsRegistry(t.from) = updatedFrom
accountsRegistry(t.to) = updatedTo
t.succeed()
}
}
})