Cats-effects' IO class is the answer of the library to performing side effects (or simply effects) in a functional way. Functional programming is focused on pure functions and a pure function is a function that does not perform any side effects but only produces an output based on the receiving inputs. Real-world programs are far from this mathematical abstract definition. A program with no side effects is doing nothing as most of the useful things are side effects, such as writing to a database, writing to a file, reading from a file, printing on the screen, and ...
An IO class is actually a description of a computation, rather than the execution of that computation. That's why it will not make a function an impure function.
Example:
Printing on the screen (which is a side effect), as some sort of logging.
If we want to print on the screen using inside the body of a function the side effect happens but if we return the effect as an IO object wrapping the calculation result, then we have a pure function that delegates the effects to its caller.
Bad function (not pure function):
def notPureMultiple(a: Int, b: Int): Int = {
// some kind of logging inside the function
println(s"not pure: calculating $a * $b")
a * b
}Good function (pure function):
def pureMultiple(a: Int, b: Int): IO[Int] = {
IO {
println(s"pure: calculating $a * $b")
a * b
}
}Complete code:
package com.blogspot.scaland7.catseffects
import cats.effect.IO
import cats.effect.unsafe.implicits.global
object SideEffects01 {
def notPureMultiple(a: Int, b: Int): Int = {
// some kind of logging inside the function
println(s"not pure: calculating $a * $b")
a * b
}
def pureMultiple(a: Int, b: Int): IO[Int] = {
IO {
println(s"pure: calculating $a * $b")
a * b
}
}
def main(args: Array[String]): Unit = {
// this calculates the result and do the side effect right away, which is not good!
val value1: Int = notPureMultiple(10, 20)
// this return an IO of the result so the side effect has not happened until we run the io
val value2: IO[Int] = pureMultiple(20, 10)
value2.unsafeRunSync() // effects happens here
}
}
For cats-effects dependency add the following line to your build.sbt file
libraryDependencies += "org.typelevel" %% "cats-effect" % "3.4.8"
Comments
Post a Comment