# [derives clause] what's the difference between derives and given in object

Hello, i have some question about `derives` clause.
`derives` generate typeclass in target type companion object, what’s the different from given in companion object?
There is an example in official document.

• if i give a recursive type, the Eq trait works when use derives explicitly
• but it fails after i remove the `derives` clause.

After removing the derives cluase, it still works for types that not recursive.
So, anyone knows why?

``````import scala.deriving.*
import scala.compiletime.{erasedValue, summonInline}

inline def summonAll[T <: Tuple]: List[Eq[_]] =
inline erasedValue[T] match
case _: EmptyTuple => Nil
case _: (t *: ts) => summonInline[Eq[t]] :: summonAll[ts]

trait Eq[T]:
def eqv(x: T, y: T): Boolean

object Eq:
given Eq[Int] with
def eqv(x: Int, y: Int) = x == y

given Eq[String] with
def eqv(x: String, y: String) = x == y

def check(elem: Eq[_])(x: Any, y: Any): Boolean =
elem.asInstanceOf[Eq[Any]].eqv(x, y)

def iterator[T](p: T) = p.asInstanceOf[Product].productIterator

def eqSum[T](s: Mirror.SumOf[T], elems: => List[Eq[_]]): Eq[T] =
new Eq[T]:
def eqv(x: T, y: T): Boolean =
val ordx = s.ordinal(x)
(s.ordinal(y) == ordx) && check(elems(ordx))(x, y)

def eqProduct[T](p: Mirror.ProductOf[T], elems: => List[Eq[_]]): Eq[T] =
new Eq[T]:
def eqv(x: T, y: T): Boolean =
iterator(x).zip(iterator(y)).zip(elems.iterator).forall {
case ((x, y), elem) => check(elem)(x, y)
}

inline given derived[T](using m: Mirror.Of[T]): Eq[T] =
lazy val elemInstances = summonAll[m.MirroredElemTypes]
inline m match
case s: Mirror.SumOf[T]     => eqSum(s, elemInstances)
case p: Mirror.ProductOf[T] => eqProduct(p, elemInstances)
end Eq

enum Tree[T] derives Eq { // works with derives but fails when remove the derives clause
case Branch(left: Tree[T], right: Tree[T]) // a recursive type
case Leaf(elem: T)
}

@main def hello: Unit =
summon[Eq[Tree[Int]]].eqv(Tree.Leaf(1),Tree.Leaf(1))
``````