Skip to content
Scala

隐式参数(Scala 3 中为 Given/Using)

通过隐式参数实现类型类派生和上下文传递。

#implicit#type-class#scala3

Code

scala
// Type class definition
trait Show[A] {
  def show(a: A): String
}

// Instance
implicit val showInt: Show[Int] = (a: Int) => a.toString

// Usage (implicit parameter)
def printIt[A](a: A)(implicit s: Show[A]): Unit =
  println(s.show(a))

printIt(42)  // "42" — compiler finds showInt

// Scala 3 syntax:
// given Show[Int] with { def show(a: Int) = a.toString }
// def printIt[A](a: A)(using s: Show[A]): Unit = ...