Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

SCALA FUNCTIONS EXAMPLES

• Partially Applied Function


• Higher order function
Consider the case where we want to print out the student results that include the stream he/she is in and
the class level(4th year, 3rd year etc).
The stream and class level are the same. So a partially applied function can apply in this case.
Also we can have a higher order function the receives a function the returns the grade of given marks

object PAFExample {
def main(args: Array[String])={

val str="StreamA"
val classlevel="4th year"
//A variable to hold the results . The stresult function is partially applied.
val printstresults=stresult(str,classlevel,_ :Int)
printstresults(56)
printstresults(34)
printstresults(67)

//Calling the higher order function


println(result(grade,76))
}//end of main

//A function to print out the results


def stresult(stream: String,clss: String, mark: Int) = {
println(stream +"----"+clss +"---" + grade(mark))
}

// A higher order function API. It recieves a function fn whose argument is an Int and returns a
string. It also recives an Int argument (mark). Then it applies the fn function to the argument
mark
def result(fn: Int=>String, mark: Int) = fn(mark)

// A function to return the grade


def grade(mark:Int): String={
if( mark >= 70 )"A" else if( mark >= 60 )"B" else if( mark >= 50 )"C"
else
if( mark >= 40 )"D" else "F"
}//End of grade
}

You might also like