Skip to main content
Version: 2.x

Introduction to ZIO's Built-in Services

ZIO already provides four built-in services:

  1. Console โ€” Operations for reading/writing strings from/to the standard input, output, and error console.
  2. Clock โ€” Contains some functionality related to time and scheduling.
  3. Random โ€” Provides utilities to generate random numbers.
  4. System โ€” Contains several useful functions related to system environments and properties.

All four follow the same design: a service trait, a companion object with a Tag and accessor methods, a Live implementation, and a synchronous UnsafeAPI. See Anatomy of a Built-in Service for how that shared design works.

When we use these services, we don't provide them to our effects. ZIO keeps the four Live implementations in a fiber-local set of default services whose initial contents are DefaultServices.live, and every accessor, such as Clock.currentDateTime, reads its service from there. See How These Services Reach Your Program for the details.

import zio._

import java.io.IOException

object MainApp extends ZIOAppDefault {
val myApp: ZIO[Any, IOException, Unit] =
for {
date <- Clock.currentDateTime
_ <- ZIO.logInfo(s"Application started at $date")
_ <- Console.print("Enter your name: ")
name <- Console.readLine
_ <- Console.printLine(s"Hello, $name!")
} yield ()

def run = myApp
}

myApp uses both Clock and Console, yet its type is ZIO[Any, IOException, Unit]: built-in services never appear in the environment type, because their accessors read them from the fiber's default services, not from the environment.

Testing These Servicesโ€‹

Each of these four services has a deterministic test double โ€” TestClock, TestConsole, TestRandom, and TestSystem โ€” that ZIO Test installs as the fiber's default service in place of the live implementations, behind the same trait, so code written against Clock, Console, Random, and System is testable without any changes. See Testing These Services for how each test double works.

See Alsoโ€‹

  • Anatomy of a Built-in Service โ€” The shared trait/companion/Live/UnsafeAPI design behind all four services.
  • Writing ZIO Services โ€” Guide to ZIO Service Pattern: define maintainable services using interfaces and ZLayer for automatic dependency injection.

ZIO Chat

๐Ÿ”ฅ Ignite your ZIO journey with ZIO Chat! ๐Ÿ”ฅ Ready to unravel the intricacies of ZIO? As your trusty sidekick, I'm here to light the way. No matter if you're wandering through functional forests or traversing effectful landscapes, I've got answers to keep you on track. Your ZIO adventure starts here โ€“ ask me anything and let's explore together!