0Pricing
Scala for Backend Engineering & Functional Programming · Урок

Монада IO

Чистые эффекты

«Монада IO» — бесплатный урок Scala for Backend Engineering & Functional Programming на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Scala for Backend Engineering & Functional Programming, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Scala for Backend Engineering & Functional Programming содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

What Is IO?

IO[A] from Cats Effect is a description of a computation that, when run, may perform side effects and produce a value of type A. It is a pure value — nothing happens until you run it.

Deferring Side Effects

Wrap a side effect with IO(...) or IO.delay(...). The body is not executed when the IO is created — only when it is run.

import cats.effect.IO

val program: IO[Unit] = IO(println("Hello, IO!"))
// Nothing printed yet — program is just a description

Referential Transparency

Because IO is lazy, you can substitute an IO value for its definition without changing behavior. This referential transparency makes effectful code easier to reason about and refactor.

Pure Values

Use IO.pure to lift an already-computed value. Do not put side effects inside pure — it evaluates eagerly. Use IO.delay or IO(...) for effects.

import cats.effect.IO

val p: IO[Int] = IO.pure(42)
// 42 is computed already; pure just wraps it

map and as

map transforms the result of an IO. as replaces it with a constant. Neither runs the effect — they build a bigger description.

import cats.effect.IO

val len: IO[Int] = IO("hello").map(_.length)
val done: IO[String] = IO(println("ran")).as("done")

Running with IOApp

To execute an IO program, extend IOApp and implement run, returning an IO[ExitCode]. The runtime evaluates it on a fiber-based scheduler.

import cats.effect.{IO, IOApp, ExitCode}

object Main extends IOApp {
  def run(args: List[String]): IO[ExitCode] =
    IO(println("Running!")).as(ExitCode.Success)
}

IOApp.Simple

For programs without args or custom exit codes, extend IOApp.Simple and provide a run: IO[Unit].

import cats.effect.{IO, IOApp}

object Hello extends IOApp.Simple {
  def run: IO[Unit] = IO.println("Hello, world!")
}

IO.println

Cats Effect provides IO.println as a convenient effectful print. It returns IO[Unit] and only prints when run.

import cats.effect.IO

val greet: IO[Unit] = IO.println("effectful output")

Capturing Exceptions

If the wrapped effect throws, the failure is captured inside the IO instead of escaping. The IO becomes a failed value you can later handle.

import cats.effect.IO

val boom: IO[Int] = IO(throw new RuntimeException("fail"))
// Creating boom does NOT throw; running it would

Plain Scala Comparison

Without an effect type, side effects run immediately and are hard to compose. IO defers them, so a self-contained Scala program prints eagerly while IO would defer.

object Main {
  def main(args: Array[String]): Unit = {
    val eager = println("runs now") // executed immediately
    println("second line")
  }
}

Why Use IO?

IO gives you:

  • Purity — effects are values
  • Composability — build programs from small pieces
  • Safety — errors and resources are tracked
  • Concurrency — lightweight fibers

Quick Check

When does the side effect inside IO(println("hi")) actually execute?

Recap

The IO monad models effects as pure, lazy values:

  • IO(...) / IO.delay defer effects
  • IO.pure wraps computed values
  • IOApp / IOApp.Simple run programs
  • Exceptions are captured, not thrown eagerly

Next: composing multiple IO actions together.

Часто задаваемые вопросы

Урок «Монада IO» бесплатный?

Да — полный текст урока «Монада IO» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Scala for Backend Engineering & Functional Programming, подпишись на CoddyKit PRO. Курс Scala for Backend Engineering & Functional Programming содержит 4 уроков всего.

Чему я научусь в уроке «Монада IO»?

Чистые эффекты Ты практикуешь Scala for Backend Engineering & Functional Programming с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Scala for Backend Engineering & Functional Programming?

Предыдущий опыт не требуется. Scala for Backend Engineering & Functional Programming на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Монада IO»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Scala for Backend Engineering & Functional Programming?

Да. Каждый урок Scala for Backend Engineering & Functional Programming включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Классы типов Cats
  2. Монада IO
  3. Композиция IO
  4. Обработка ошибок в IO
← Назад к Scala for Backend Engineering & Functional Programming