Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scheme cond in scala language

Tags:

scala

Does scala have an equivalent to scheme's cond?

like image 323
bb2 Avatar asked Nov 06 '10 02:11

bb2


2 Answers

I guess you're looking for match (or just simply if/else if/else).

like image 115
steinar Avatar answered Oct 20 '22 18:10

steinar


case class Paired(x: Int, y: Int)

def foo(x: Any) = x match {
  case string : String => println("Got a string")
  case num : Int if num < 100 => println("Number less than 100")
  case Paired(x,y) => println("Got x and y: " + x + ", " + y)
  case unknown => println("??: " + unknown)
}

The first two case statements show type based pattern matching. The third shows the use of an Extractor to break data down into constituent parts and to assign those parts to variables. The third shows a variable pattern match which will match anything. Not shown is the _ case:

case _ => println("what")

Which like the variable pattern match, matches anything, but does not bind the matched object to a variable.

The case class at the top is Scala shorthand for creating an extractor as well as the class itself.

like image 45
Collin Avatar answered Oct 20 '22 18:10

Collin