It is possible that a given instance extends another one?

I have a base trait and a child trait. Inside base trait object scope I’ve already provided some instances.

trait BaseTrait[T] {
    def f(a:T, b: T): T 
}
object BaseTrait {
    def apply[T](using ev: BaseTrait[T]): BaseTrait[T] = ev
    given IntBaseTrait: BaseTrait[Int] = new BaseTrait[Int] {
        def f(a: Int, b: Int): Int = a + b * 10
    }
}
trait ChildTrait[T] extends BaseTrait[T] {
    def cf: T
}
object ChildTrait {
    given c: ChildTrait[Int] = new ChildTrait[Int] {
        override def f(a: Int, b: Int): Int = a + b * 10 // I want to use the one provided in BaseTrait object scope
        override def cf: T = f(1, 2) + f(3, 4)
    }
}

Now in the child trait object scope, I also have a given instance but I also want to extends the functionality from the base trait, instead of duplicating a redundant function at the child trait.

I tried

import BaseTrait._
given c: ChildTrait[Int] = new ChildTrait[Int] with IntBaseTrait[Int] {...}

But this produces Not found: type IntBaseTrait. which is expected. Any way to achieve this effect?

Thanks

The general convention as of Scala 2 is to don’t provide an instance of BaseTrait[Int] just ChildTrait[Int]

There are some people investigating different encodings for Scala 3 but for now the convention remains.

1 Like

This in scala 2, I assume it should be the similar in scala 3.
You can extend BaseTrait[int] in another trait and mix in that with ChildTrait[Int]

trait BaseTraitInt extends BaseTrait[Int] {
      def f(a: Int, b: Int): Int = a + b * 10
    }

implicit val ChildTraitInt: ChildTrait[Int] =
      new BaseTraitInt with ChildTrait[Int] {
        def cf: Int = f(1, 2) + f(3, 4)
      }
1 Like

Didn’t know such convention. Thanks for the information!

Thanks for the suggestion!

You can also add a dependency on the base given, with a using clause:

object ChildTrait {
  given c(using base: BaseTrait[Int]): ChildTrait[Int] = new ChildTrait[Int] {
      override def f(a: Int, b: Int): Int = base.f(a, b)
      override def cf: Int = f(1, 2) + f(3, 4)
  }
}

2 Likes