Search code examples
scalatype-members

Establish bounds for type members within a type alias in Scala


Given:

trait Record {
  type ID
  val id: ID
}

trait DataSource {
  type ID
  def read(id: ID): Try[R]
}

I'd like to be able to describe the read function generically.

type Reader[R <: Record, DS <: DataSource] = (DS#ID) => Try[R]

How can I guarantee type safety here such that DS#ID won't be a dissimilar type as R#ID? I tried...

type Reader[R <: Record, DS <: DataSource, R#ID <: DS#ID] = (DS#ID) => Try[R]

But that doens't compile. What is the correct syntax for this situation?


Solution

  • When dealing with the type parameters of Reader, ID has to be pulled out as it's own parameter.

    type Reader[R <: Record, DS <: DataSource, ID] = (ID) => Try[R]
    

    Once this is done it's possible to then place additional bounds onto it...

    type Reader[R <: Record, DS <: DataSource, ID <: DS#ID =:= R#ID] = (ID) => Try[R]