Skip to content

Instantly share code, notes, and snippets.

@shihpeng
Last active August 29, 2015 14:22
Show Gist options
  • Save shihpeng/509adcbc4d7e1b3a87b0 to your computer and use it in GitHub Desktop.
Save shihpeng/509adcbc4d7e1b3a87b0 to your computer and use it in GitHub Desktop.
Scala Control Structures
def echoWhatYouGiveMe(x: Any): String = x match {
// constant patterns
case 0 => "zero"
case true => "true"
case "hello" => "you said 'hello'"
case Nil => "an empty List"
// sequence patterns
case List(0, _, _) => "a three-element list with 0 as the first element"
case List(1, _*) => "a list beginning with 1, having any number of elements"
case Vector(1, _*) => "a vector starting with 1, having any number of elements"
// tuples
case (a, b) => s"got $a and $b"
case (a, b, c) => s"got $a, $b, and $c"
// constructor patterns
case Person(first, "Alexander") => s"found an Alexander, first name = $first"
case Dog("Suka") => "found a dog named Suka"
// typed patterns
case s: String => s"you give me this string: $s"
case i: Int => s"thanks for the int: $i"
case f: Float => s"thanks for the float: $f"
case a: Array[Int] => s"an array of int: ${a.mkString(",")}"
case as: Array[String] => s"an array of strings: ${as.mkString(",")}"
case d: Dog => s"dog: ${d.name}"
case list: List[_] => s"thanks for the List: $list"
case m: Map[_, _] => m.toString
// the default wildcard pattern
case _ => "Unknown"
}
object LabeledBreakDemo extends App {
import scala.util.control._
val Inner = new Breaks
val Outer = new Breaks
Outer.breakable {
for(i <- 1 to 5) {
Inner.breakable {
for(j <- 'a' to 'e') {
if(i == 1 && j == 'c') Inner.break else println(s"i: $i, j: $j")
if(i == 2 && j == 'b') Outer.break
}
}
}
}
}
import scala.util.control._
val Exit = new Breaks
Exit.breakable {
for(j <- 'a' to 'e'){
if (j == 'c') Exit.break else println(s"j: $j")
}
}
import scala.annotation.switch
class SwitchDemo {
// When writing simple match expression like this, it's recommend to use the @switch annotation.
// This annotation provides a warning at compile time if the switch can't be compiled to a tableswitch or lookupswitch.
val i = 1
val x = (i: @switch) match {
case 1 => "One"
case 2 => "Two"
case _ => "Other"
}
/*
* The following conditions must be true for Scala to apply the tableswitch optimization:
* 1. The matched value must be a known integer.
* 2. The matched expression must be "simple." It can't contain ant type checks, if statements, or extractors.
* 3. The expression must also have its value available at compile time.
* 4. There should be more than two case statements.
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment