1

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?

Victor Basso
  • 5,556
  • 5
  • 42
  • 60
  • I suppose, some of us just love nesting ... What if it is `Seq[Seq[Seq[Seq[Seq[Int]]]]`? – Dima Jul 06 '17 at 00:22

2 Answers2

3

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.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
1

To answer your first question - isEmpty comes from internals of Option type.

def unapply = f means - create a parameterless method that returns a function. This is not a method by itself and thus you have an error.

You can further read about difference between function and method in Scala there: Difference between method and function in Scala

bottaio
  • 4,963
  • 3
  • 19
  • 43