Reading this, I still have questions about unapply() that returns Boolean.
If take a look at Scala Programming Book (2nd edition), page 602. There is an example:
case Email(Twice(x @ UpperCase()), domain) => ...
Where UpperCase defined as an object that has unapply() returning Boolean and does not have apply()
object UpperCase {
def unapply(s:String): Boolean = s.toUpperCase == s
}
Where Twice is something like this:
object Twice {
def apply(s:String): String = s + s
...
The questions are (must be too many, sorry for that):
How does UpperCase().unapply(..) works here?
If I pass: [email protected], then x in first code snippet = 'DI'.. then we use '@' ..to bind 'x' to pass it to UpperCase.unapply to invoke unapply(x) i.e unapply('DIDI') (?) Then it returns True.
But why not Option ? I tend to think that unapply returns Option.. kind of one way how it works. That's probably because usually Option wraps some data, but for simple case we should NOT wrap boolean? And because we do not have apply()?
What the difference, when use Boolean / Option ? Based on this example.
And this syntax: x @ UpperCase(), is it supposed to substitute value match case (is that way how I suppose to read it?) syntax if we are matching inside one particular case? It doesn't seems as unified way/syntax of doing this.
Usually syntax like (assuming that x,y is Int): case AA(x @ myX, y) => println("myX: " + myX) says that x binds to myX, basically myX is alias to x.. in this case. But in our case - x @ UpperCase(). x binds to UpperCase().unapply().. putting x as parameter. I mean binding here is quite abstract/wide notion..
This is simple:
1) If you return Boolean, your unapply just tests matching query
2) If you return Option[T], you create an extractor, which unwraps T