I read The Neophyte's Guide to Scala Part 5: The Option Type and he suggested that a way to match on options. I implemented his suggestion here:
s3Bucket match {
case Some(bucket) =>
bucket.putObject(partOfKey + key + file.getName, file)
true
case None =>
false
}
But I have some questions on how it actually works. Namely, since s3Bucket
is of type Option[Bucket]
, how does case Some(bucket)
unwrap s3Bucket
into bucket
? What exactly is going on under the hood?
Scala's pattern matching statement is most useful for matching on algebraic types expressed via case classes. Scala also allows the definition of patterns independently of case classes, using unapply methods in extractor objects.
Pattern matching is a way of checking the given sequence of tokens for the presence of the specific pattern. It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C.
Pattern matching tests whether a given value (or sequence of values) has the shape defined by a pattern, and, if it does, binds the variables in the pattern to the corresponding components of the value (or sequence of values). The same variable name may not be bound more than once in a pattern.
As we know getOrElse method is the member function of Option class in scala. This method is used to return an optional value. This option can contain two objects first is Some and another one is None in scala. Some class represent some value and None is represent a not defined value.
The short answer is: extractors.
What's an extractor? I won't go into details here, but - in short- an extractor is a method capable of destructuring an instance of a type, extracting a value from it.
In scala any A
that provides an unapply
method with this signature
def unapply(object: A): Option[B]
can be used in pattern matching, where it will extract a value of type B
if the matches succeeds.
There's plenty of resources online you can read about this mechanism. A good one is this blog post by Daniel Westheide.
Back to your question, Some
and None
both provide an unapply
method by the virtue of being case classes (which automatically extend Product
), so they can be used in pattern matching.
A sketchy implementation would go pretty much like:
object Some {
def unapply[A](a: Some[A]) = Some(a.get)
}
object None {
def unapply(object: None) = None
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With