4. Type classes in Haskell
class Comparable a where
cmp :: a -> a -> Bool
instance Comparable Int where
cmp x y = x < y
instance Comparable a => Comparable [a] where
cmp xs ys = cmp (head xs) (head ys)
cmp (1 :: Int) 2
cmp [1 :: Int, 2] [2, 0]
> True
Dmytro Mitin Type classes
5. Implicits in Scala
Implicit parameters
def f(x: Int)(implicit y: String): String = x.toString + y
implicit val s: String = "abc"
f(10)
> 10abc
Implicit objects
class MyClass
def f(x: Int)(implicit y: MyClass): Int = x + y.hashCode
// implicit val obj = new MyClass
implicit object obj extends MyClass
f(10)
> ... /* some number */
Dmytro Mitin Type classes
6. Implicits in Scala
Implicit conversions
implicit def f(x: Int): String = x.toString + "abc"
def g(s: String): List[Char] = s.toList
g(123)
> List(1, 2, 3, a, b, c)
Implicit classes
implicit class MyClass(x: Int) {
def myMethod: Int = x + 1
}
123.myMethod
> 124
Dmytro Mitin Type classes
7. Type classes in Scala
trait Comparable[A] {
def cmp(a1: A, a2: A): Boolean
}
implicit object intComparable extends Comparable[Int] {
override def cmp(a1: Int, a2: Int): Boolean = a1 < a2
}
implicit class ComparableInt(x: Int) {
def cmp(y: Int): Boolean =
implicitly[Comparable[Int]].cmp(x, y)
}
Dmytro Mitin Type classes