Defining Instances
Implicit instances.
Defining Instances
An instance tells the compiler how a type class behaves for a specific type. In Scala, instances are usually marked implicit (Scala 2) or declared with given (Scala 3) so they are found automatically.
An implicit val Instance
For a simple type class, an implicit val is enough. The compiler finds it when a function needs a Show[Int].
trait Show[A] { def show(a: A): String }
object Main {
implicit val intShow: Show[Int] = (a: Int) => s"Int=$a"
def display[A](a: A)(implicit s: Show[A]): String = s.show(a)
def main(args: Array[String]): Unit = {
println(display(123))
}
}All lessons in this course
- The Type Class Pattern
- Defining Instances
- Common Type Classes
- Type Class Derivation