Overview
In scala, functions are first class values. You can store function value, pass function as an argument and return function as a value from other function. You can create function by using def keyword. You must mention return type of parameters while defining function and return type of a function is optional. If you don’t specify return type of a function, default return type is Unit.
Syntax
0 1 2 3 4 |
def functionName(parameters : typeofparameters) : returntypeoffunction = { // statements to be executed } |
You can create function with or without
Scala Function Example without using = Operator
The function defined below is also known as non parameterized function.
0 1 2 3 4 5 6 7 8 9 |
object MainObject { def main(args: Array[String]) { functionExample() // Calling function } def functionExample() { // Defining a function println("This is a simple function") } } |
Scala Function Example with = Operator
0 1 2 3 4 5 6 7 8 9 10 11 |
object MainObject { def main(args: Array[String]) { var result = functionExample() // Calling function println(result) } def functionExample() = { // Defining a function var a = 20 a } } |
Scala Parameterized Function Example
when using parameterized function you must mention type of parameters explicitly otherwise compiler throws an error and your code fails to compile.
0 1 2 3 4 5 6 7 8 9 10 |
object MainObject { def main(args: Array[String]) = { functionExample(20,20) } def functionExample(a:Int, b:Int) = { var c = a+b println(c) } } |
Function Parameter with Default Value
Let’s see an example.
0 1 2 3 4 5 6 7 8 9 10 11 12 |
object MainObject { def main(args: Array[String]) = { var result1 = functionExample(11,4) // Calling with two values var result2 = functionExample(12) // Calling with one value var result3 = functionExample() // Calling without any value println(result1+"\n"+result2+"\n"+result3) } def functionExample(a:Int = 0, b:Int = 0):Int = { // Parameters with default values as 0 a+b } } |
Scala Function Named Parameter Example
In scala function, you can specify the names of parameters during calling the function. In the given example, you can notice that parameter names are passing during calling. You can pass named parameters in any order and can also pass values only.
Let’s see an example.
0 1 2 3 4 5 6 7 8 9 10 11 12 |
object MainObject { def main(args: Array[String]) = { var result1 = functionExample(a = 11, b = 4) // Parameters names are passed during call var result2 = functionExample(b = 11, a = 4) // Parameters order have changed during call var result3 = functionExample(11,4) // Only values are passed during call println(result1+"\n"+result2+"\n"+result3) } def functionExample(a:Int, b:Int):Int = { a+b } } |
That’s all for Functions in Scala. Happy Learning!!