trait HasEnv {
def env: Map[String, String]
}
def readEnv(name: String): zio.ZIO[HasEnv, Throwable, String] =
.ZIO.environmentWithZIO { r =>
zio.ZIO.attempt {
zio.get.env(name)
r}
}
trait HasReadLn {
def readLn(): String
}
def readLn: zio.ZIO[HasReadLn, Throwable, String] =
.ZIO.environmentWithZIO { r =>
zio.ZIO.attempt {
zio.get.readLn()
r}
}
trait HasWrite {
def write(output: String): Unit
}
def write(output: String): zio.ZIO[HasWrite, Throwable, Unit] =
.ZIO.environmentWithZIO { r =>
zio.ZIO.attempt {
zio.get.write(output)
r}
}
def enProgram: zio.ZIO[HasReadLn with HasWrite, Throwable, Unit] =
for {
<- write("What's your name? ")
_ <- readLn
name <- write(s"Hello, ${name}!\n")
_ } yield ()
def esProgram: zio.ZIO[HasReadLn with HasWrite, Throwable, Unit] =
for {
<- write("¿Cómo te llamas? ")
_ <- readLn
name <- write(s"¡Hola, ${name}!\n")
_ } yield ()
def program: zio.ZIO[HasEnv with HasReadLn with HasWrite, Throwable, Unit] =
for {
<- readEnv("LANG")
lang <- if (lang.startsWith("es")) {
_
esProgram} else {
enProgram}
} yield ()
.Unsafe.unsafely {
zio//zio.Unsafe.unsafe { implicit u: zio.Unsafe =>
.Runtime.default.unsafe.run(
zio.provide(
program.ZLayer.succeed(
zionew HasEnv {
override def env: Map[String, String] = sys.env
}
),
.ZLayer.succeed(
zionew HasReadLn {
override def readLn(): String = scala.io.StdIn.readLine()
}
),
.ZLayer.succeed(
zionew HasWrite {
override def write(output: String): Unit = print(output)
}
)
)
).getOrThrowFiberFailure()
}
This file is literate Scala, and can be run using Codedown:
$ LANG=es_MX.UTF-8 scala-cli --scala 3.2.2 --dependency dev.zio::zio:2.0.6 \
<(curl https://earldouglas.com/posts/effect-systems/zio.md | codedown scala)
¿Cómo te llamas? James
¡Hola, James!