ZIO is a zero-dependency Scala library for asynchronous and concurrent programming with comprehensive effect system.
npx @tessl/cli install tessl/maven-dev-zio--zio_2-12@2.1.00
# ZIO
1
2
ZIO is a zero-dependency Scala library for asynchronous and concurrent programming, powered by highly-scalable, non-blocking fibers. It provides a comprehensive effect system with the core `ZIO[R, E, A]` type representing async workflows that require an environment `R` and can fail with `E` or succeed with `A`. ZIO features high-performance concurrent operations, type-safe error handling, resource management that prevents leaks, comprehensive testing capabilities, and functional programming primitives.
3
4
## Package Information
5
6
- **Package Name**: dev.zio:zio_2.12
7
- **Package Type**: Maven
8
- **Language**: Scala
9
- **Installation**: `libraryDependencies += "dev.zio" %% "zio" % "2.1.19"`
10
11
## Core Imports
12
13
```scala
14
import zio._
15
import zio.ZIO._
16
```
17
18
For specific components:
19
20
```scala
21
import zio.{ZIO, ZLayer, Runtime, Fiber, Ref, Queue, Schedule, Cause, Chunk}
22
import zio.stm.{ZSTM, TRef, TMap, TQueue}
23
import zio.stream.{ZStream, ZSink, ZPipeline}
24
import zio.test.{Spec, ZIOSpecDefault, Assertion, Gen, TestAspect}
25
import zio.metrics.{Metric, MetricClient, MetricLabel}
26
```
27
28
## Basic Usage
29
30
```scala
31
import zio._
32
33
// Simple effect that always succeeds
34
val greeting: UIO[String] = ZIO.succeed("Hello, ZIO!")
35
36
// Effect that might fail
37
val mayFail: IO[String, Int] = ZIO.attempt {
38
"123".toInt // Could throw NumberFormatException
39
}.refineOrDie {
40
case _: NumberFormatException => "Invalid number"
41
}
42
43
// Combining effects
44
val program: ZIO[Any, String, Unit] = for {
45
message <- greeting
46
number <- mayFail
47
_ <- Console.printLine(s"$message Number: $number")
48
} yield ()
49
50
// Running the program
51
object MyApp extends ZIOAppDefault {
52
def run = program
53
}
54
```
55
56
## Architecture
57
58
ZIO is built around several key architectural components:
59
60
- **Effect System**: Core `ZIO[R, E, A]` type representing typed effects with environment, error, and success types
61
- **Runtime System**: Execution environment with fiber-based concurrency, scheduling, and resource management
62
- **Layer System**: Dependency injection via `ZLayer` for composable service provisioning
63
- **STM**: Software Transactional Memory for lock-free concurrent programming
64
- **Type Safety**: Comprehensive type system preventing common concurrency and resource management errors
65
- **Zero Dependencies**: Pure Scala implementation with no external runtime dependencies
66
67
## Type System
68
69
ZIO provides a rich type alias system for common effect patterns:
70
71
```scala { .api }
72
// Core effect types
73
type IO[+E, +A] = ZIO[Any, E, A] // No requirements
74
type Task[+A] = ZIO[Any, Throwable, A] // May fail with Throwable
75
type RIO[-R, +A] = ZIO[R, Throwable, A] // Requires R, may fail
76
type UIO[+A] = ZIO[Any, Nothing, A] // Cannot fail
77
type URIO[-R, +A] = ZIO[R, Nothing, A] // Requires R, cannot fail
78
79
// Layer type aliases
80
type RLayer[-RIn, +ROut] = ZLayer[RIn, Throwable, ROut]
81
type URLayer[-RIn, +ROut] = ZLayer[RIn, Nothing, ROut]
82
type Layer[+E, +ROut] = ZLayer[Any, E, ROut]
83
type ULayer[+ROut] = ZLayer[Any, Nothing, ROut]
84
type TaskLayer[+ROut] = ZLayer[Any, Throwable, ROut]
85
```
86
87
## Capabilities
88
89
### Core Effect System
90
91
The foundational ZIO effect type and operations for building functional, concurrent applications with comprehensive error handling and resource safety.
92
93
```scala { .api }
94
sealed trait ZIO[-R, +E, +A] {
95
// Core transformations
96
def map[B](f: A => B): ZIO[R, E, B]
97
def flatMap[R1 <: R, E1 >: E, B](k: A => ZIO[R1, E1, B]): ZIO[R1, E1, B]
98
def mapError[E2](f: E => E2): ZIO[R, E2, A]
99
100
// Error handling
101
def catchAll[R1 <: R, E2, A1 >: A](h: E => ZIO[R1, E2, A1]): ZIO[R1, E2, A1]
102
def orElse[R1 <: R, E2, A1 >: A](that: => ZIO[R1, E2, A1]): ZIO[R1, E2, A1]
103
def retry[R1 <: R, S](policy: => Schedule[R1, E, S]): ZIO[R1, E, A]
104
105
// Concurrency
106
def fork: URIO[R, Fiber.Runtime[E, A]]
107
def race[R1 <: R, E1 >: E, A1 >: A](that: => ZIO[R1, E1, A1]): ZIO[R1, E1, A1]
108
def timeout(d: => Duration): ZIO[R, E, Option[A]]
109
}
110
111
// Factory methods
112
object ZIO {
113
def succeed[A](a: => A): UIO[A]
114
def fail[E](error: => E): IO[E, Nothing]
115
def attempt[A](code: => A): Task[A]
116
def async[R, E, A](register: (ZIO[R, E, A] => Unit) => Any): ZIO[R, E, A]
117
}
118
```
119
120
[Core Effects](./core-effects.md)
121
122
### Dependency Injection
123
124
ZLayer system for building and composing services with compile-time dependency resolution and automatic resource management.
125
126
```scala { .api }
127
sealed abstract class ZLayer[-RIn, +E, +ROut] {
128
// Composition operators
129
def ++[E1 >: E, RIn2, ROut2](that: => ZLayer[RIn2, E1, ROut2]): ZLayer[RIn with RIn2, E1, ROut with ROut2]
130
def >>>[E1 >: E, ROut2](that: => ZLayer[ROut, E1, ROut2]): ZLayer[RIn, E1, ROut2]
131
def >+>[E1 >: E, ROut2](that: => ZLayer[ROut, E1, ROut2]): ZLayer[RIn, E1, ROut with ROut2]
132
133
// Lifecycle
134
def build: ZIO[RIn with Scope, E, ZEnvironment[ROut]]
135
def launch: ZIO[RIn, E, Nothing]
136
}
137
138
object ZLayer {
139
def succeed[A: Tag](a: => A): ULayer[A]
140
def fromZIO[R, E, A: Tag](zio: => ZIO[R, E, A]): ZLayer[R, E, A]
141
def scoped[R]: ScopedPartiallyApplied[R]
142
}
143
```
144
145
[Dependency Injection](./dependency-injection.md)
146
147
### Concurrency Primitives
148
149
Fiber-based lightweight concurrency with atomic data structures for building high-performance concurrent applications.
150
151
```scala { .api }
152
// Fiber - lightweight threads
153
sealed abstract class Fiber[+E, +A] {
154
def await: UIO[Exit[E, A]]
155
def join: IO[E, A]
156
def interrupt: UIO[Exit[E, A]]
157
def zip[E1 >: E, B](that: => Fiber[E1, B]): Fiber.Synthetic[E1, (A, B)]
158
}
159
160
// Ref - atomic reference
161
sealed abstract class Ref[A] {
162
def get: UIO[A]
163
def set(a: A): UIO[Unit]
164
def modify[B](f: A => (B, A)): UIO[B]
165
def update(f: A => A): UIO[Unit]
166
}
167
168
// Queue - concurrent queue
169
sealed abstract class Queue[A] {
170
def offer(a: A): UIO[Boolean]
171
def take: UIO[A]
172
def size: UIO[Int]
173
}
174
```
175
176
[Concurrency](./concurrency.md)
177
178
### Error Handling and Scheduling
179
180
Comprehensive error model with rich failure causes and composable retry/repeat scheduling for resilient applications.
181
182
```scala { .api }
183
// Rich error representation
184
sealed abstract class Cause[+E] {
185
def failures: List[E]
186
def defects: List[Throwable]
187
def &&[E1 >: E](that: Cause[E1]): Cause[E1] // parallel composition
188
def ++[E1 >: E](that: Cause[E1]): Cause[E1] // sequential composition
189
}
190
191
// Retry/repeat scheduling
192
trait Schedule[-Env, -In, +Out] {
193
def &&[Env1 <: Env, In1 <: In, Out2](that: Schedule[Env1, In1, Out2]): Schedule[...]
194
def ||[Env1 <: Env, In1 <: In, Out2](that: Schedule[Env1, In1, Out2]): Schedule[...]
195
def jittered: Schedule[Env, In, Out]
196
}
197
198
object Schedule {
199
val forever: Schedule[Any, Any, Long]
200
def exponential(base: Duration): Schedule[Any, Any, Duration]
201
def spaced(duration: Duration): Schedule[Any, Any, Long]
202
}
203
```
204
205
[Error Handling](./error-handling.md)
206
207
### Resource Management
208
209
Scope-based resource lifecycle management with automatic cleanup and finalizer execution for leak-free applications.
210
211
```scala { .api }
212
sealed trait Scope {
213
def addFinalizer(finalizer: => UIO[Any]): UIO[Unit]
214
def addFinalizerExit(finalizer: Exit[Any, Any] => UIO[Any]): UIO[Unit]
215
def fork: UIO[Scope.Closeable]
216
}
217
218
// Resource-safe operations
219
def acquireRelease[R, E, A, B](
220
acquire: => ZIO[R, E, A]
221
)(release: A => URIO[R, Any]): ZIO[R with Scope, E, A]
222
223
def ensuring[R1 <: R](finalizer: => URIO[R1, Any]): ZIO[R1, E, A]
224
```
225
226
[Resource Management](./resource-management.md)
227
228
### Software Transactional Memory
229
230
Lock-free concurrent programming with composable transactional operations and automatic retry mechanisms.
231
232
```scala { .api }
233
// Transactional effects
234
sealed trait ZSTM[-R, +E, +A] {
235
def commit: ZIO[R, E, A]
236
def map[B](f: A => B): ZSTM[R, E, B]
237
def flatMap[R1 <: R, E1 >: E, B](f: A => ZSTM[R1, E1, B]): ZSTM[R1, E1, B]
238
def retry: USTM[Nothing]
239
}
240
241
// Transactional reference
242
sealed abstract class TRef[A] {
243
def get: USTM[A]
244
def set(a: A): USTM[Unit]
245
def modify[B](f: A => (B, A)): USTM[B]
246
}
247
248
object ZSTM {
249
def atomically[R, E, A](stm: ZSTM[R, E, A]): ZIO[R, E, A]
250
}
251
```
252
253
[Software Transactional Memory](./stm.md)
254
255
### Built-in Services
256
257
Standard services for common application needs including console I/O, time operations, randomness, and system access.
258
259
```scala { .api }
260
// Console operations
261
def printLine(line: => Any): IO[IOException, Unit]
262
def readLine: IO[IOException, String]
263
264
// Time operations
265
def currentTime(unit: => TimeUnit): UIO[Long]
266
def sleep(duration: => Duration): UIO[Unit]
267
def nanoTime: UIO[Long]
268
269
// Random generation
270
def nextInt: UIO[Int]
271
def nextUUID: UIO[UUID]
272
def nextBytes(length: => Int): UIO[Chunk[Byte]]
273
274
// System access
275
def env(variable: => String): IO[SecurityException, Option[String]]
276
def property(prop: => String): Task[Option[String]]
277
```
278
279
[Built-in Services](./services.md)
280
281
### Application Framework
282
283
Complete application framework with dependency injection, configuration, and lifecycle management for building production applications.
284
285
```scala { .api }
286
trait ZIOApp {
287
type Environment
288
def bootstrap: ZLayer[ZIOAppArgs, Any, Environment]
289
def run: ZIO[Environment with ZIOAppArgs with Scope, Any, Any]
290
}
291
292
// Default application base
293
abstract class ZIOAppDefault extends ZIOApp {
294
type Environment = Any
295
final def bootstrap: ZLayer[ZIOAppArgs, Any, Any] = ZLayer.empty
296
}
297
298
// Application helpers
299
def getArgs: ZIO[ZIOAppArgs, Nothing, Chunk[String]]
300
def exit(code: ExitCode): UIO[Unit]
301
```
302
303
[Application Framework](./application.md)
304
305
### ZIO Streams
306
307
Composable, resource-safe streaming data processing with comprehensive backpressure handling and error recovery for building data pipelines and reactive applications.
308
309
```scala { .api }
310
// Core streaming types
311
sealed trait ZStream[-R, +E, +A]
312
sealed trait ZSink[-R, +E, -In, +L, +Z]
313
sealed trait ZPipeline[-R, +E, -In, +Out]
314
315
// Type aliases
316
type Stream[+E, +A] = ZStream[Any, E, A]
317
type UStream[+A] = ZStream[Any, Nothing, A]
318
319
// Stream construction
320
def fromIterable[A](as: => Iterable[A]): UStream[A]
321
def fromZIO[R, E, A](zio: => ZIO[R, E, A]): ZStream[R, E, A]
322
def repeat[A](a: => A): UStream[A]
323
```
324
325
[ZIO Streams](./streams.md)
326
327
### Testing Framework
328
329
Comprehensive testing framework with property-based testing, test services, and seamless integration with ZIO effects for testing concurrent and async code.
330
331
```scala { .api }
332
// Test specifications
333
sealed trait Spec[-R, +E]
334
abstract class ZIOSpec[R] extends ZIOApp
335
abstract class ZIOSpecDefault extends ZIOSpec[Any]
336
337
// Assertions and property testing
338
sealed trait Assertion[-A]
339
sealed trait Gen[+R, +A]
340
def assertTrue(condition: => Boolean): TestResult
341
def check[R, A](gen: Gen[R, A])(test: A => TestResult): ZIO[R, Nothing, TestResult]
342
343
// Test services
344
trait TestClock extends Clock
345
trait TestConsole extends Console
346
trait TestRandom extends Random
347
```
348
349
[Testing Framework](./testing.md)
350
351
### Metrics and Observability
352
353
Comprehensive metrics and observability capabilities for monitoring application performance, collecting telemetry data, and gaining insights into system behavior.
354
355
```scala { .api }
356
// Metric system
357
sealed trait Metric[In, Out]
358
trait MetricClient
359
case class MetricLabel(key: String, value: String)
360
361
// Metric types
362
def counter(name: String): Metric[Double, MetricState.Counter]
363
def gauge(name: String): Metric[Double, MetricState.Gauge]
364
def histogram(name: String, boundaries: Boundaries): Metric[Double, MetricState.Histogram]
365
366
// Built-in metrics
367
val jvmMemoryUsed: Metric[Any, MetricState.Gauge]
368
val fiberCount: Metric[Any, MetricState.Gauge]
369
```
370
371
[Metrics and Observability](./metrics.md)