Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 25, 2024 10:20
Show Gist options
  • Save dacr/c3c0f5bac9a5517bdb1eb8ec307e3401 to your computer and use it in GitHub Desktop.
Save dacr/c3c0f5bac9a5517bdb1eb8ec307e3401 to your computer and use it in GitHub Desktop.
ZIO live session - Writing a simple application - legacy versus effect-based / published by https://github.com/dacr/code-examples-manager #b354e541-49ea-4c6c-aa60-a6497b0ac72f/8665375cc4c964a2c5b387ecbf8dfffc12ea172e
// summary : ZIO live session - Writing a simple application - legacy versus effect-based
// keywords : scala, zio, live, demo, pure-functional, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : b354e541-49ea-4c6c-aa60-a6497b0ac72f
// created-on : 2021-09-26T16:27:18+02:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.4.2"
//> using dep "org.slf4j:slf4j-simple:2.0.7"
//> using dep "dev.zio::zio:2.0.13"
//> using dep "dev.zio::zio-nio:2.0.1"
//> using dep "fr.janalyse::zio-worksheet:2.0.13.0"
// ---------------------
// =========================================================================================
// classic legacy code
{
import org.slf4j.LoggerFactory
import scala.io.Source
def app() =
val logger = LoggerFactory.getLogger("default")
logger.info("Application starts")
val fileContent = Source.fromFile("live-04.sc").getLines()
val count = fileContent.size
logger.info("line count is {}", count)
logger.info("Application ends")
println(count)
println(app())
}
// =========================================================================================
// effect based programming
{
import zio.*, zio.worksheet.*
import zio.nio.file.*
val app = for {
_ <- ZIO.log("Application starts")
lines <- Files.readAllLines(Path("live-04.sc"))
count = lines.size
_ <- ZIO.log(s"line count is $count")
_ <- ZIO.log("Application ends")
_ <- Console.printLine(count)
} yield ()
app.unsafeRun
}
// - both are readable in the same way !
// - but the second one is quite safer, the type signature tells us that it can fail
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment