Don't forget to also checkout my second blog containing articles to all other related ICT topics!!

Friday, May 25, 2012

Scala promotes expression oriented programming

Scala promotes immutability and expression-oriented programming. Most scala constructs return a value as we will come to see in following examples.
First let's take a look at type matching:
scala> def replyMessage(message:Any): Any = message match {
     |     case s:String => "Your message is the string " + s
     |     case i:Int => "Your message is the number " + i
     |     case _ => "Your message is of unknown type"
     | }
replyMessage: (message: Any)Any

scala> replyMessage("Hello world")
res1: Any = Your message is the string Hello world

scala> replyMessage(5)
res2: Any = Your message is the number 5

scala> replyMessage(true)
res3: Any = Your message is of unknown type

Next let's take a look regular pattern matching using Fibonacci as an example
scala> def fibonacci(n: Int): Int = n match {
     |     case 0 => 0
     |     case 1 => 1
     |     case _ => fibonacci(n-2) + fibonacci(n-1)
     | }
fibonacci: (n: Int)Int

scala>

scala> (for (n <- 0 to 10) yield fibonacci(n)).toList
res15: List[Int] = List(0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55)

Also the if-else construct returns a value
scala> val fname = "Robby"
fname: java.lang.String = Robby

scala> if (fname.startsWith("B")) "Your name does start with B" else "Hey Mr R"
res19: java.lang.String = Hey Mr R

As a rule of thumb, just remember that you can omit the return statement. Scala will return the last expression in a block statement.
scala> def someComplexMethod(n: Int): Int = {
     |     val x = "blabla"
     |     n * 2
     | }
someComplexMethod: (n: Int)Int

scala>

scala> someComplexMethod(3)
res22: Int = 6

No comments:

Post a Comment