Show
The Show type class is an abstraction that provides the ability to convert values of any type
into their string representation.
It is an alternative to the toString method that allows flexible customization of output formatting for various data types.
The Show type class defines one primary operation:
show— a function that takes a value of typeAand returns its string representation of typeString.
Where is it used?
- Logging:
Logs often need to output values of various types in a readable format.
Showallows customizing formatting for each type. - Debugging:
When debugging code,
Showcan be used to output values in a developer-friendly format. - Custom output:
In applications that need to display data to users,
Showallows customizing formatting depending on the context (e.g., displaying numbers with a specific number of decimal places). - Serialization:
Showcan be used to convert data to strings before saving or transmitting over a network.
Advantages over toString:
- Flexibility:
Showallows customizing the string representation for each type separately. - Safety:
Showis independent of thetoStringimplementation, which may be inconvenient or unsafe (e.g.,toStringfor arrays in Java outputs a hash code). - Extensibility:
Showcan be implemented for any types, including third-party libraries, without modifying their source code.
Formal definition
Show is a type class that provides an abstraction for converting objects into their string representation.
For a correct implementation of Show, the following laws must hold:
- Consistency: For any value
xof typeA,show(x)should return the same string representation on every call. - Readability: The string representation should be understandable and useful to a human.
Code definition in Scala
trait Show[A]:
def show(a: A): String
- Type parameter
A:Showis parameterized by typeAfor which string representation is defined. showmethod: Theshowmethod takes a value of typeAand returns its string representation.
Implementation in libraries
Implementation in Cats
import cats.*
import cats.implicits.*
123.show // 123
"abc".show // abc
Implementation in ScalaZ
import scalaz.*
import Scalaz.*
1.0.shows // "1.0"
References: