Skip to main content

Posts

Showing posts from November, 2012

Pattern matching in Scala

One cool feature I  learned a few days ago in Scala was Pattern Matching. It lets you decompose into a virtual switch..case statement any input object or variable, to easily do different things in different cases Example funciton that returns true if the input is an empty List, otherwise false. This is not obviosuly a good way to implement this feature, but this post is just to demonstrate the pattern matching in action. def func(x: List[Int]): Boolean = {     x match {       case List() => true // if x matches this pattern return true       case List(x: Int) => false // not needed, but for demo of another pattern match       case _ => false // default case     }   }                                                   So this returns true   func(List())                                    // > res5: Boolean = true these return false  func(List(2))  func(List(1,2,2)) Here is another one that matches based on the number of arg