DennisVDB
DennisVDB

Reputation: 1367

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 CallEquityOptionand 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?

Upvotes: 1

Views: 131

Answers (1)

Jasper-M
Jasper-M

Reputation: 15086

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

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

Upvotes: 3

Related Questions