DennisVDB DennisVDB - 2 months ago 7
Scala Question

Default type class implementation in trait for sub-classes in Scala

I have the following relations:

trait Instrument

trait EquityOption extends Instrument { ... }
case class CallEquityOption(...) extends EquityOption
case class PutEquityOption(...) extends EquityOption

trait Priceable[I <: Instrument] { def price(I : Instrument) }


I can use exactly the same implementation of
Priceable
for the case classes
CallEquityOption
and
PutEquityOption
. By having a
match case
to differentiation between the
Call...
and
Put...
. However, if I try to implement it directly as
Priceable[EquityOption]
under
object EquityOption
, the implicit cannot be found since it doesn't exactly match the type.

How can I make it work without needing to duplicate code?

Answer

You'll have to prove that you can provide an instance for every subtype of EquityOption.

implicit def allEquityOptions[T <: EquityOption]: Pricable[T] = ???
Comments