the blog for developers

Scala Goodness: Extractors

One Scala goodness is the unapply method to extract values.

Suppose we want to match a string if it does contain DogFood. In Scala we can use an object or class with an unapply method, which takes the input we try to extract values from and returns the extracted value. Because there needn’t be a match in every case, the value is wrapped in an Option. A simple extractor for DogFood might look like this:

object DogFood {
  def unapply(f:String):Option[String] =
    if (f=="meat") Some("MEAT!") else None
}

// Prints "Yeah MEAT!"
"meat" match {
  case DogFood(f) => println ("Yeah " + f)
  case _ => println ("Bah")
}
// Prints "Bah"
"fruit" match {
  case DogFood(f) => println ("Yeah " + f)
  case _ => println ("Bah")
}

The unapply method can be used in more contexts. Another usecase is to filter for comprehensions. The same DogFood object from above can be used to filter a list of Strings and only return Strings that contain dog food:

scala> val foods = List("meat","fruit","grain")
foods: List[java.lang.String] = List(meat, fruit, grain)

scala> for (DogFood(f) <- foods) yield f
res29: List[String] = List(MEAT!)

Unapply can extract more than one value. In such a case, the method needs to return a Tuple (Javaish):

case class Food(food:String)
case class Name(name:String)

object Dog {
  def unapply(desc:String):Option[(Name,Food)] = {
    val i=desc.indexOf(" eats ")
    if (i> -1)
      Some((Name(desc.substring(0,i)), Food(desc.substring(i+6))))
    else None
  }
}

We can now use the Dog object to extract more than one value:

scala> "Brutus eats meat" match { case Dog(f,n) => (f,n) }
res5: (Name, Food) = (Name(Brutus),Food(meat))

This also works for assignment, just as with Tuple assignment:

scala> val Dog(f,n) = "Brutus eats meat"
f: Name = Name(Brutus)
n: Food = Food(meat)

Extractors in Scala even work with Squences. For an example see Daily Scala, a wonderful blog with Scala tips.

See also:

You can leave a Reply here. Of course, you should follow me on twitter here.

You can share this post!
Do you want to tell others about this article? Use the social bookmark icons to submit this artice to the service of your choice. Thanks.

About the author: Stephan Schmidt has more than 15 years of internet technology experience and 10 years experience in agile. He was head of development, consultant and CTO and is a speaker, author and blog writer. He specializes in organizing and optimizing software development helping companies by increasing productivity with lean software development and agile methodologies. Want to know more? All views are only his own.

8 Tweets

Leave a reply.

Comments

Great post, simple and concise.

@Slim: Thanks

Leave a Reply

What people wrote somewhere else:

Scala Goodness: Extractors http://codemonkeyism.com/scala-goodness-extractors/

This comment was originally posted on Twitter

Code Monkeyism: Scala Goodness: Extractors http://ff.im/-eVQCk

This comment was originally posted on Twitter

@johlrogge Funny, I thought about dogs today, Dog(n:Name, f:Food), agree n:Name wouldn’t make sense for cats ;-) http://bit.ly/afdEg6

This comment was originally posted on Twitter

RT @codemonkeyism Code Monkeyism: Scala Goodness: Extractors http://bit.ly/boaxRM

This comment was originally posted on Twitter

Scala Goodness: Extractors – http://su.pr/4yNa1f

This comment was originally posted on Twitter

Code Monkeyism: Scala Goodness: Extractors http://ff.im/-eZKYs

This comment was originally posted on Twitter

Code Monkeyism: Scala Goodness: Extractors http://ff.im/-f01et

This comment was originally posted on Twitter

Code Monkeyism: Scala Goodness: Extractors http://ff.im/-fwW2u

This comment was originally posted on Twitter

Additional comments powered by BackType

Guide to CodeMonkeyism

Over the last 4 years I wrote many articles on this blog. To make it easier for you to find the relevant ones, I've organized them into topics.

Top 10

6 reasons why my VC funded startup did fail

Go Ahead: Next Generation Java Programming Style

Java Interview questions: Write a String Reverser

The dark side of NoSQL

7 Bad Signs not to Work for a Software Company or Startup

Is Java dead?

Scala vs. Clojure

Never, never, never use String in Java

No future for functional programming in 2008 – Scala, F# and Nu

Clojure vs Scala, Part 2

Java Developer

Is Java Dead?

Go Ahead: Next Generation Java Programming Style

Be careful with magical code

All variables in Java must be final

Never, never, never use String in Java

Bending Java: More readable code with methods that do nothing?

NoSQL Guy

NoSQL: The Dawn of Polyglot Persistence

The dark side of NoSQL

Essential storage tradeoff: Simple Reads vs. Simple Writes

Sharding destroys the goals of your relational database

The unholy legacy of databases

Startup/CTO

Development Dream Teams

6 reasons why my VC funded startup did fail

American vs. European style of Software Development

12 Things to Reduce Your Lead Time and Time to Market

The high cost of overhead when working in parallel

Essential storage tradeoff: Simple Reads vs. Simple Writes

Job Seeker

Another Good (Java) Interview Question

7 Bad Signs not to Work for a Software Company or Startup

Java Interview questions: Write a String Reverser (and use Recursion!)

Java Interview questions: Multiple Inheritance

As a Manager: What I value in developers

Top 10 Tips (+1) to Get a Pay Raise

Agilist

What Developers Need to Know About Agile

5 Practices Better to Change in Your Scrum Implementation

Scrum is not about engineering practices

ScrumMaster and ZenMaster: The joke of certification

What is Trans-Scrum?