Scala case example

“Case” is used very frequently in Scala, as it is much more useful than other languages.

For instance, you might wish to make a lambda that is defined only some of the time. This is convenient for writing tools to do ETL or scraping, where you don’t know how to handle some value, and aren’t sure if it will ever actually occur – you’ve defined that you know it could exist, but without actually handling it:

val y = (x: Int) => { 
  x match { 
     case 1 => "test" 
     case 2 => ???
     case _ => ??? 
  } 
}

This is what the output looks like:

y: Int => String = 

scala> y(1)
res8: String = test

scala> y(2)
scala.NotImplementedError: an implementation is missing
  at scala.Predef$.$qmark$qmark$qmark(Predef.scala:225)
  at $anonfun$1.apply(:8)
  at $anonfun$1.apply(:8)
  ... 33 elided

scala> y(3)
scala.NotImplementedError: an implementation is missing
  at scala.Predef$.$qmark$qmark$qmark(Predef.scala:225)
  at $anonfun$1.apply(:8)
  at $anonfun$1.apply(:8)
  ... 33 elided

Note how the ??? is actually a special operator, which causes “NotImplementedError” for “any” value (the _ matches whatever is left).

Case can match on types:

1 match { case _: Int => "int" }

res18: String = int

And on regexes:

val pattern = "(\\d*)".r
"1" match { case pattern(x) => "int" }

res31: String = int

The most common use case for “case” is unpacking lists of values. Usually these are “case classes”, which are similar to the concept of dictionary entries or enumeration types (except that a case class can hold data, like “Some” here holding a 1):

Some(1)
  match { 
    case Some(x) => x 
    case _ => "nothing" 
  }

res37: Any = 1

Leave a Reply

Your email address will not be published. Required fields are marked *