scalaextractorunapply

Why can't I reuse "unapply" without repeating the method signature


The following Scala code compiles fine:

val f = (input: String) => Some("result")
object Extract {
   def unapply(input: String): Option[String] = f(input)
}
val Extract(result) = "a string"

But if I replace the extractor by:

object Extract {
   def unapply = f
}

Then compilation fails with:

error: an unapply result must have a member `def isEmpty: Boolean
val Extract(result) = "a string"
    ^

Why? Where does def isEmpty: Boolean come from?


Solution

  • In Scala 2.10 (and before) unapply had to always return an Option or a Boolean. Since 2.11, it can return any type, so far as it has def isEmpty: Boolean and def get: <some type> methods (like Option does). See https://hseeberger.wordpress.com/2013/10/04/name-based-extractors-in-scala-2-11/ for an explanation why it's useful. But your unapply returns a String => Some[String], which doesn't have either, and that's what the error says.