Last active
May 6, 2023 15:39
-
-
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/6b5da3d68ad53960c3b1419a366800f7b6741d22
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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.2.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