How to model interdependency between fields of a case class?

Viewed 93

I would like to model some interdependency between fields of a case class such that the possible values of the rhs field would depend on the type of lhs.

In the example below, I had not managed to write type B = A.B - it would not compile, only type B = A#B. Not surprisingly, in the example below this line does compile: SomeDomain.Foo(SomeDomain.Brr, SomeDomain.Bee.Pooh) though this defeats the purpose.

Evidently I am doing something wrong. Is there a small fix here? Or, should I take a different approach altogether?

// Entering paste mode (ctrl-D to finish)

trait Domain {
  trait Bar {
    type B
  }
  type A <: Bar
  type B = A#B

  case class Foo(lhs: A, rhs: B)
}

object SomeDomain extends Domain {
  sealed trait Baz extends Bar {
    sealed trait Inner

    override type B = Inner
  }

  case object Brr extends Baz {

    case object Strawberry extends Inner
    case object Raspberry extends Inner
  }

  case object Bee extends Baz {

    case object Honey extends Inner
    case object Pooh extends Inner
  }

  override type A = Baz
}


val foo = SomeDomain.Foo(SomeDomain.Brr, SomeDomain.Bee.Pooh)
val f1= foo.lhs
val f2 = foo.rhs

// Exiting paste mode, now interpreting.

defined trait Domain
defined object SomeDomain
foo: SomeDomain.Foo = Foo(Brr,Pooh)
f1: SomeDomain.A = Brr
f2: SomeDomain.B = Pooh
1 Answers
Related