/***
+= "dev.zio" %% "zio" % "1.0.0-RC19-2"
libraryDependencies */
trait HasEnv {
def env: Map[String, String]
}
def readEnv(name: String): zio.ZIO[HasEnv, Throwable, String] =
.ZIO fromFunctionM { r =>
zio.ZIO effect {
zio.env(name)
r}
}
trait HasReadLn {
def readLn(): String
}
val readLn: zio.ZIO[HasReadLn, Throwable, String] =
.ZIO fromFunctionM { r =>
zio.ZIO effect {
zio.readLn()
r}
}
trait HasWrite {
def write(output: String): Unit
}
def write(output: String): zio.ZIO[HasWrite, Throwable, Unit] =
.ZIO fromFunctionM { r =>
zio.ZIO effect {
zio.write(output)
r}
}
val enProgram: zio.ZIO[HasReadLn with HasWrite, Throwable, Unit] =
for {
<- write("What's your name? ")
_ <- readLn
name <- write(s"Hello, ${name}!\n")
_ } yield ()
val esProgram: zio.ZIO[HasReadLn with HasWrite, Throwable, Unit] =
for {
<- write("¿Cómo te llamas? ")
_ <- readLn
name <- write(s"¡Hola, ${name}!\n")
_ } yield ()
val program: zio.ZIO[HasEnv with HasReadLn with HasWrite, Throwable, Unit] =
for {
<- readEnv("LANG")
lang <- if (lang.startsWith("es")) {
_
esProgram} else {
enProgram}
} yield ()
.Runtime.default.unsafeRun {
zio.provide {
programnew HasEnv with HasReadLn with HasWrite {
override val env: Map[String, String] = sys.env
override def readLn(): String = scala.io.StdIn.readLine()
override def write(output: String): Unit = print(output)
}
}
}
This file is literate Scala, and can be run using Codedown:
$ curl https://earldouglas.com/posts/effect-systems/zio.md |
codedown scala > script.scala
$ LANG=es sbt -Dsbt.main.class=sbt.ScriptMain script.scala
¿Cómo te llamas? James
¡Hola, James!