Scala case class unapply

After so many SKBs, you pretty much are an expert !

So, let's dive into a more advanced concept.

And particularly, about one more features of thecase classrelated on how pattern matching works.

We have seen previously how, withcase class, you can extract the component of it and match specific values. Have you ever wondered how it was built ? If yes, today is your lucky day ! If not, then you are going to learn it anyway.

The answer is the special methodunapply. Similarly toapply,unapplyhas specific use case and behavior.

unapplyallows you to extract parts of “something” in the context of apattern matching.

The syntax can be very confusing. Let's look at it in details. Everything that needs to be replace for your specific use case is in between[ ].

Declaration:

object [PATTERN_MATCHING_NAME] {

def unapply(input: [INPUT_TYPE]): Option[[OUTPUT_TYPE]] = {

// to match, must return:

Some([output_value])

// to 'pass'

None

}

}

We are going to see the notion of 'pass' in a later SKB

How it is used:

val input: [INPUT_TYPE] = ???

input match {

case [PATTERN_MATCHING_NAME]([OUTPUT_TYPE]) => ???

}

What is confusing is when[OUTPUT_TYPE]is a tuple. Because in theunapplydefinition, it will be written something like(Int, String)but in the usage, in the pattern matching, it will be writtenPATTERN_MATCHING_TYPE(a: Int, b: String)and NOTPATTERN_MATCHING_TYPE(a : (Int, String)).

This syntax works for every pattern matching, which means it also works inmap,flatMapand all.

You might imagine other possible use case forunapplyand you are right. In our example, we only reproduced what thecase classwas doing but we can do much more. We are going to see more advanced usage ofunapplyin upcoming SKBs.

Reveal more information and clues
Load Exercise