Type Class for Related Types

Viewed 78

Let's say we have the following traits:

trait MyValue
object MyValue {
  case class MyBoolean(record: Boolean) extends MyValue
  case class MyLong(record: Long) extends MyValue
}

trait MyValueExtractor[T] {
  def apply(record: T): Option[MyValue]
}

trait MyThing[T] {
  def name: String
  def myValueExtractor: MyValueExtractor[T]
  def myValue(record: T): Option[MyValue] = myValueExtractor(record)
}

What I want is something like this but without the second type parameter. Note: I can't actually update the MyThing trait; I'm just using this as an illustration of the intended functionality.

trait MyThing[T, U] {
  def name: String
  def myValueExtractor: MyValueExtractor[T]
  def myValue(record: T): Option[MyValue] = myValueExtractor(record)
  def myRelatedValue(record: T): Option[U]
}

I'm wondering if I could use the type class pattern to help solve this (i.e., import some rich class that implicitly gives me a myRelatedValue method)?

Here's the rub. Every time T (above) is MyValue.MyBoolean, U must be a String. Every time T is MyValue.MyLong, U must be a Double. In other words, there's a sort of underlying mapping between T and U.

Is there a good way to do this using type class?

1 Answers
Related