Scala Extractors

Scala’s extractors and unapply() represent a concept that I haven’t grok’ed until now.

Most demonstrations seem to be too long or use the same types everywhere. Here are my thoughts on the concept;

val a: C = ???
val i: I = ???

i match {
    case a(f: O) =>
        ???
}

This will try to call the below method

class C {
    def unapply(i: I): Option[O] =
        ???
}

There’s some more flexibility;

  • the I in unapply(i: I) can be <: I
  • you can do the @ matching by returning Boolean
  • there’s the super weird infix notation

… but nothing that seems challenging anymore. Methods are chosen by their name and parameters, so you can’t have two methods which are different by their return type only. The compiler handles unpacking into tuples … I think … and values that are tested but not captured … seem … sensible.

comments powered by Disqus
Peter LaValle avatar
Peter LaValle
Any links probably include affiliate ids for that sweet sweet kickback - and some programs require that I tell you. The contents of this blog are likely unrelated - as they include games, paints, and build tools.