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 the case class related on how pattern matching works.

We have seen previously how, with case 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 method unapply. Similarly to apply, unapply has specific use case and behavior.

unapply allows you to extract parts of “something” in the context of a pattern 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 the unapply definition, it will be written something like (Int, String) but in the usage, in the pattern matching, it will be written PATTERN_MATCHING_TYPE(a: Int, b: String) and NOT PATTERN_MATCHING_TYPE(a : (Int, String)).

This syntax works for every pattern matching, which means it also works in map, flatMap and all.

You might imagine other possible use case for unapply and you are right. In our example, we only reproduced what the case class was doing but we can do much more. We are going to see more advanced usage of unapply in upcoming SKBs.

Reveal more information and clues
Load Exercise