Sunday, September 18, 2016

Nested / Local Function : Example...

scala> // Nested / Local Function #182

scala> // Helps to avoid namespace pollution

scala> // Recommended : Helper functions can be created as a

scala> //               Nested function

scala> def getMarks(subList: List[String]): List[Int] = {
     |
     |    def getMark(subject: String):Int = {
     |       subject match {
     |          case "history" => 75
     |          case "math" => 80
     |          case _ => 70
     |       }
     |    }
     |
     |    for (sub <- subList) yield {
     |       //Note : It is also possible to access the Function
     |       //Parameter
     |       println("Checking subject List " + subList.length)
     |       getMark(sub)
     |    }
     | }
getMarks: (subList: List[String])List[Int]

scala>

scala> val subList = List("history", "math", "science")
subList: List[String] = List(history, math, science)

scala> getMarks(subList)
Checking subject List 3
Checking subject List 3
Checking subject List 3
res82: List[Int] = List(75, 80, 70)