ZIO Cheat Sheet

November 25, 2018

https://github.com/zio/zio

sbt configuration

/***
libraryDependencies += "dev.zio" %% "zio" % "1.0.0-RC12-1"
*/

Type aliases

A program with side-effects

val program1: zio.Task[java.util.Date] =
  for {
    now <- zio.ZIO.effect { new java.util.Date() }
    _   <- zio.ZIO.effect { println(now) }
  } yield now
val runtime1: zio.Runtime[_] = new zio.DefaultRuntime {}
val now: java.util.Date = runtime1.unsafeRun(program1)
println(now)

A program with dependencies

case class Config(x: Int, y: Int)

trait ConfigIO {
  def config: Config
}
val program2: zio.ZIO[ConfigIO, Throwable, Int] =
  zio.ZIO fromFunctionM { r =>
    zio.ZIO effect {
      r.config.x * r.config.y
    }
  }
val runtime2: zio.Runtime[ConfigIO] =
  zio.Runtime( new ConfigIO {
                 val config: Config =
                   Config( x = 6
                         , y = 7
                         )
               }
             , zio.internal.PlatformLive.Default
             )
println(runtime2.unsafeRun(program2))

Demo

This file is literate Scala, and can be run using Codedown:

$ curl -s https://earldouglas.com/posts/reference/zio.md |
  codedown scala > script.scala
$ sbt -Dsbt.main.class=sbt.ScriptMain script.scala
Sat Jul 13 13:55:05 MDT 2019
42