0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

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

  1. The Type Class Pattern
  2. Defining Instances
  3. Common Type Classes
  4. Type Class Derivation
← Back to Scala for Backend Engineering & Functional Programming