score:3

Accepted answer

Good question. I don't think you can do what you want directly.

One alternative approach is trait IntStrDependent extends Dependent[Either[Int, String]] but that doesn't quite solve the problem. Maybe a variant of Miles Sabin's encoding of union types allows something fancier to be done.

I think the best option is to keep it simple,

trait Dependent[T]{
  def observeCritereaChanged(oldValue:T, newValue:T):Unit
}

trait IntStrDependent {
  val I: Dependent[Int]
  val S: Dependent[String]
}

object MyDependent extends IntStrDependent {
  object I extends Dependent[Int] {
    def observeCritereaChanged(oldValue:Int, newValue:Int) {}
  }
  object S extends Dependent[String] {
    def observeCritereaChanged(oldValue:String, newValue:String) {}
  }
}

To use MyDependent, one must explicitly select the Int or String variant, as in

MyDependent.I.observeCritereaChanged(1, 2)

In my opinion, making the type dependence explicit is a good thing anyway.


Related Query

More Query from same tag