Abdul Rahman Abdul Rahman - 19 days ago 15
Scala Question

Type classes for polymorphic data types in scala

So I have a polymorphic data type Tree in scala defined as follows

sealed trait Tree[+A]
final case class Node[A](value: A) extends Tree[A]
final case class Branch[A](value: A, left: Tree[A], right: Tree[A]) extends Tree[A]

object Tree{

implicit def eqTree[T]: Eq[Tree[T]] = new Eq[Tree[T]] {
override def ==(t1: Tree[T], t2: Tree[T]): Boolean = true
}
}


And a type class Eq

trait Eq[T]{

def == (t1: T, t2: T) : Boolean
}


And I am trying to do

object App1 extends App{

import Tree._

def equality[T](t1: T1, t2: T2)(implicit eq: Eq[T]): Boolean = eq.==(t1, t2)

println(equality(Node(1), Node(2)))
}


However I get the following error

Error:(35, 19) could not find implicit value for parameter eq: typeclasses.Eq[typeclasses.Node[Int]]
println(equality(Node(1), Node(2)))

Answer

As the error says, compiler is trying to find Eq[Node[Int]], and there is no such value in scope. You have defined Eq[Tree[T]].

So basically this is what compiler sees:

equality[Node[Int]](Node(1), Node(2))

But you actually want this:

println(equality[Tree[Int]](Node(1), Node(2)))