Read

Read is a type class that provides an abstraction for converting strings into objects of a specific type. It is the inverse operation of the Show type class and is used for parsing strings into values.

Where is it used?

Usage examples:

Advantages:

Alternative to standard methods:

Unlike methods like Integer.parseInt, Read provides a more universal and type-safe approach, helping avoid errors related to incorrect string format.

Formal definition

Read is a type class that provides an abstraction for converting strings into objects of a specific type. The read function takes a string and returns the type that is a member of Read.

For a correct implementation of Read, the following laws must hold:

Code definition in Scala

trait Read[F]:
  def read(s: String): Either[String, F]

Usage example

object Read:
  given Read[Int] with
    def read(s: String): Either[String, Int] =
      s.toIntOption.toRight(s"Invalid integer: $s")

summon[Read[Int]].read("42")
// Right(42)
summon[Read[Int]].read("abc")
// Left("Invalid integer: abc")

References: