Skip to content

Instantly share code, notes, and snippets.

@razorjack
Created May 12, 2012 20:50
Show Gist options
  • Save razorjack/2668943 to your computer and use it in GitHub Desktop.
Save razorjack/2668943 to your computer and use it in GitHub Desktop.
Pattern Matching in Scala
import java.util.Date
import java.text.DateFormat
import java.text.DateFormat._
val echoMath = """^echo (.*)""".r
val countMath = """^count from (\d) to (\d)""".r
while (true) {
print("> ") // prompt
scala.io.Source.stdin.getLine(0) match {
case "hello" =>
println("hi")
case "time" =>
val currentDate = new Date
val df = getDateInstance(LONG)
println(df format currentDate)
case echoMath(str) =>
println(str)
case countMath(a, b) =>
val m = a.toInt
val n = b.toInt
for (i <- (m to n)) {
print(i + ", ")
}
println("boom!")
case "exit" =>
println("bye")
sys.exit
case _ => println("command not matched")
}
}
@razorjack
Copy link
Author

Example session:

> hello
hi
> time
May 12, 2012
> count from 1 to 7
1, 2, 3, 4, 5, 6, 7, boom!
> echo are you there?
are you there?
> sudo make me a sandwich
command not matched
> exit
bye

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment