scala oops context-abstractions
Type classes
A type class or trait is an abstract class taking a generic type.
trait UtilMath[T]:
def add(x: T, y: T): T
So, UtilMath
is a type class.
Implementing a Type class
A type classes can be implemented using two methods
- Extending the type class using
extends
- Creating a context using
given with
Extending a type class
object StringMath extends UtilMath[String]:
def add(x: String, y: String): String = x + y
given with
given UtilMath[String] with
def add(x: String, y: String): String = x + y
Now, UtilMath[String]
will be implicitly inferred by the compiler.
summon[UtilMath[String]].add("hello ", "world")
Read about given instance for given
keyword.