IO

IO is a type class that represents an abstraction for working with input/output (I/O) in functional programming. It allows describing I/O operations without executing them immediately, which helps avoid side effects and makes code more predictable and testable.

Where is it used?

Advantages:

Formal definition

IO is a type encapsulating computations that may interact with the outside world (e.g., reading from a file, writing to a screen, networking, etc.).

Code definition in Scala

sealed trait IO[+A]:
  private[effect] def apply(rw: World[RealWorld]): Trampoline[(World[RealWorld], A)]

Implementation in libraries

Implementation in ScalaZ

import scalaz.*
import Scalaz.*
import scalaz.effect.*
import scalaz.effect.IO.*

val action1 =
  for
    x <- readLn
    _ <- putStrLn("Hello, " + x + "!")
  yield ()
action1.unsafePerformIO()

Implementation in Cats

import cats.effect.IO
import cats.effect.unsafe.implicits.global

// Define an IO action that prints a string
val printHello: IO[Unit] = IO {
  println("Hello, World!")
}

// Define an IO action that reads a string from the console
val readName: IO[String] = IO {
  scala.io.StdIn.readLine("Enter your name: ")
}

// Define an IO action that composes the previous actions
val program: IO[Unit] =
  for
    _    <- printHello
    name <- readName
    _    <- IO { println(s"Hello, $name!") }
  yield ()

// Run the program
program.unsafeRunSync()

References: