Practical Use Cases of Switch Statement in Scala

1. Catch blocks are Pattern Matches and is same as below code

    try {
        // logic
    } catch {
        case e: RuntimeException => "runtime"
        case e: NullPointerException => "npe"
        case _ => "something else"
    }

    // Catch blocks are Pattern Matches and is same as below code
    /*
    try {
        // logic
    } catch(e) {
    e match {
        case e: RuntimeException => "runtime"
        case e: NullPointerException => "npe"
        case _ => "something else"
        }
    }
     */

2. Generators are also based on pattern matching

val list = List(1, 2, 3, 4)
    val evenOnes = for {
        x <- list if x % 2 == 0 // GENERATOR
    } yield x
    println(evenOnes)

    val tuples = List((1, 2), (2, 3))
    val filterTuples = for {
        (first, second) <- tuples // extractor in this generator
    } yield first * second
    println(filterTuples)

3. Multi value definitons are based on PMs

val tuple = (1, 2, 3)
    val (a, b, c) = tuple
    println(b)

    val head :: tail = list
    println(head)
    println(tail)

4. Partial Functions are based on Pattern Matching

    val mappedList = list.map {
        case v if v % 2 == 0 => s"$v is even"
        case 1 => "One"
        case _ => "Something else "
    }
    println(mappedList)
    // Note: Partial Function is a literal inside {}

    // is same as
    val mappedList2 = list.map(x => x match {
        case v if v % 2 == 0 => s"$v is even"
        case 1 => "One"
        case _ => "Something else "
    })
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Mawazo

Mostly technology with occasional sprinkling of other random thoughts

amintabar

Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates

javaproffesionals

A topnotch WordPress.com site

thehandwritinganalyst

Just another WordPress.com site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey

%d bloggers like this: