4

I am trying to write "better" (more idiomatic?) Scala code for the following circumstance: I have a set of classes that will be identified by a reference field that belongs to a parallel set of reference case classes, something like the following:

abstract sealed class Ref(value: String)

case class ARef(value: String) extends Ref(value)
case class BRef(value: String) extends Ref(value)
case class CRef(value: String) extends Ref(value)

trait Referenced {
  type refType <: Ref
  val ref: refType
}

trait A extends Referenced { type refType = ARef }
trait B extends Referenced { type refType = BRef }
trait C extends Referenced { type refType = CRef }

Another class (which will probably turn into the state type of a State monad) will contain lists of these types, and provide a function to retrieve an object, given its reference. I want this returned value to be appropriately typed, i.e. given

val aRef = ARef("my A ref")

I want to be able to make a call like:

val myA: Option[A] = context.get[A](aRef)

and be sure to get back an Option[A], not just an Option[Referenced]. My best attempt to achieve this so far looks something like the following:

trait Context {

  // ... other stuff ...

  protected val aList: List[A]
  protected val bList: List[B]
  protected val cList: List[C]

  def get[R <: Referenced](ref: R#refType): Option[R] = {
    val result = ref match {
      case aRef: ARef => aList.find(_.ref == aRef)
      case bRef: BRef => bList.find(_.ref == bRef)
      case cRef: CRef => cList.find(_.ref == cRef)
      case _ => throw new RuntimeException("Unknown Ref type for retrieval: "+ref)
    }
    result.asInstanceOf[Option[R]]
  }
}

which seems to work correctly, but has that smelly "asInstanceOf" call in it. I would be interested in seeing ideas on how this might be done better (and check that I haven't just missed an obvious simpler solution).

Note that for other reasons, I have thus far elected to go with abstract typing rather than parameter types (trait A extends Referenced[ARef] style), but could change this if the reasons were compelling enough.

4
  • Essentially this question or this question. Perhaps you could use Shapeless's HMap. I think if you don't throw in a heavy type manipulation tool like Shapeless, you'll have to cast at some point, so your solution should be ok.
    – 0__
    Jul 8, 2013 at 8:56
  • Could Referenced be sealed as well?
    – 0__
    Jul 8, 2013 at 9:08
  • Thanks @0__, checking out those other questions I think I would agree with you - either I start pulling in Shapeless and do some heavy manipulation involving something like HMap, or accept a cast which is at least confined to within the called method. As for sealing Referenced, that works for the "toy" classes as I presented above for the purpose of the question, but in reality my intended functionality makes them much more complex beasts, defined in their own files. Jul 8, 2013 at 9:57
  • Also, if you look at the implementation, you see that it doesn't avoid casting. It just handles the "danger" for you, so you can't make mistakes.
    – 0__
    Jul 8, 2013 at 10:12

2 Answers 2

9

The machinery needed to do this without casting really isn't all that heavy in this case ... it's just another example of a functional dependency.

In what follows we rely on the fact that type Ref is sealed so that we can simply enumerate the alternatives. Your Ref and Reference hierarchies remain unchanged, and we add a relation type Rel to both express the type-level correspondence between the two, and to make an appropriate value-level selection,

trait Rel[Ref, T] {
  def lookup(as: List[A], bs: List[B], cs: List[C])(ref: Ref) : Option[T]
}

object Rel {
  implicit val relA = new Rel[ARef, A] {
    def lookup(as: List[A], bs: List[B], cs: List[C])(ref: ARef) : Option[A] =
      as.find(_.ref == ref)
  }
  implicit val relB = new Rel[BRef, B] {
    def lookup(as: List[A], bs: List[B], cs: List[C])(ref: BRef) : Option[B] =
      bs.find(_.ref == ref)
  }
  implicit val relC = new Rel[CRef, C] {
    def lookup(as: List[A], bs: List[B], cs: List[C])(ref: CRef) : Option[C] =
      cs.find(_.ref == ref)
  }
}

Now we can reimplement Context without pattern matches or casts as follows,

trait Context {

  // ... other stuff ...

  protected val aList: List[A] = ???
  protected val bList: List[B] = ???
  protected val cList: List[C] = ???

  def get[R <: Ref, T](ref: R)(implicit rel: Rel[R, T]): Option[T] =
    rel.lookup(aList, bList, cList)(ref)
}

And we can use this new definition like so,

object Test {
  def typed[T](t: => T) {}     // For pedagogic purposes only

  val context = new Context {}

  val aRef = ARef("my A ref")
  val myA = context.get(aRef)
  typed[Option[A]](myA)        // Optional: verify inferred type of myA

  val bRef = BRef("my B ref")
  val myB = context.get(bRef)
  typed[Option[B]](myB)        // Optional: verify inferred type of myB

  val cRef = CRef("my C ref")
  val myC = context.get(cRef)
  typed[Option[C]](myC)        // Optional: verify inferred type of myC
}

Notice that the resolution of the implicit Rel argument to get computes the type of the corresponding Reference from the type of the ref argument, so we're able to avoid having to use any explicit type arguments at get's call-sites.

6
  • Great! So this works if the key is sealed. Are there any other options if that was not the case, other than hiding the casting as in Shapeless' HMap?
    – 0__
    Jul 8, 2013 at 10:17
  • Casting can only be avoided if Context is indexed somehow or another by the complete set of key types. Currently that's entailed by the explicit set of key-type-specific list members (ie. aList, bList etc.). It could also be captured by parametrizing Context with the types of the keys where that's known. For that you'd want Context to be instantiated with an HList type parameter (ie. Context[A :: B :: C :: ... :: HNil]) and the individual list members would be replaced by an HList of lists of specific types ... at which point things are getting quite a bit more heavyweight. Jul 8, 2013 at 10:34
  • Ah, quite neat. On first reading I wasn't convinced about letting Ref know about the Referenced hierarchy, or exposing the typed[T] method and calls in all the places where I expect I will be making this type of call, but those are probably minor quibbles so I'll give this a try and see if I can't make the calls look cleaner. Thanks! Jul 8, 2013 at 10:48
  • @ShadowlandsI think you might be misreading slightly: I haven't changed Ref or Reference in any way so it's not the case that "Ref know(s) about the Referenced hierarchy" ... the correspondence is captured by the Rel instances. Also typed[T] is completely optional ... it's there solely to verify that type inference has done the right thing. The reason I use it is to avoid any possibility that an explicit type annotation on the val definitions might influence type inference on the RHS. Jul 8, 2013 at 10:56
  • @Miles You're right - I just realised I was reading Rel as Ref. Jul 8, 2013 at 11:00
0

I am just going to reiterate my own (current) "answer" for my question, because I thought it would be interesting/instructive to allow readers to vote it up or down to generate a more direct comparison with answers provided by others.

trait Context {

  // ... other stuff ...

  protected val aList: List[A]
  protected val bList: List[B]
  protected val cList: List[C]

  def get[R <: Referenced](ref: R#refType): Option[R] = {
    val result = ref match {
      case aRef: ARef => aList.find(_.ref == aRef)
      case bRef: BRef => bList.find(_.ref == bRef)
      case cRef: CRef => cList.find(_.ref == cRef)
      case _ => throw new RuntimeException("Unknown Ref type for retrieval: "+ref)
    }
    result.asInstanceOf[Option[R]]
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.