5

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?

2
  • 1
    you should also read about extractors in his series of articles. It's article number one danielwestheide.com/blog/2012/11/21/… Commented Aug 10, 2015 at 21:32
  • @maks thanks! I read a Scala textbook to learn Scala so I didn't actually go through the articles, I just look at them as a reference. I'll read them through now. Commented Aug 10, 2015 at 21:49

1 Answer 1

8

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.