Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Professional Scala

You're reading from   Professional Scala Combine object-oriented and functional programming to build high-performance applications

Arrow left icon
Product type Paperback
Published in Jul 2018
Publisher
ISBN-13 9781789533835
Length 186 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Ruslan Shevchenko Ruslan Shevchenko
Author Profile Icon Ruslan Shevchenko
Ruslan Shevchenko
Mads Hartmann Mads Hartmann
Author Profile Icon Mads Hartmann
Mads Hartmann
Arrow right icon
View More author details
Toc

Exploring Pattern Matching

Now we will return to pattern matching and learn about extending capabilities behind case classes. As you will remember from the previous chapter, we can use pattern matching against case classes, where fields of a class can be bound to the variables in the scope of an appropriative case clause. Can we do this for our non-case classes and embed our own custom logic for matching?

In this section, we will learn how to write our own pattern matcher and get acquainted with some standard generic classes which are often used with pattern matching.

Now, let's get started with the minimal example.

  1. First, we write the following code in the IDE:
    case class Wrapper(x:Int)
    
    w match {case Wrapper(x) => doSomething(x)}
  2. Under the hood, the compiler compiled this to the next intermediate form:
    val container = Wrapper.unapply(w)
    if (container.isDefined) {
    	val x = container.get
    	doSomething(x)
    }
    • The unapply method of the companion object is called, which must return the class...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image