IO

Implementation

class IO[A](sideEffect: => A) {
  lazy val run: A = sideEffect
  def map[B](f: A => B): IO[B] =
    new IO(f(run))
  def flatMap[B](f: A => IO[B]): IO[B] =
    new IO(f(run).run)
}

Example

val program: IO[Unit] =
  for {
    _   <- new IO(print("Type something: "))
    in  <- new IO(readLine())
    out  = "You typed: " + in
    _   <- new IO(println(out))
  } yield ()

println("Running program...")
program.run

Demo

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

$ curl https://earldouglas.com/type-classes/io.md |
  codedown scala > script.scala
$ scala -nc script.scala
Type something: Hello, IO!
You typed: Hello, IO!