Functions are group of statements that perform a task. Scala functions do look a lot like variables. The following code shows how a function can be declared.
A simple example of a function in Scala
def add(a:Int,b:Int):Int=a+b
Within the parenthesis lies the arguments followed by the argument type, after the parenthesis the return type and after the equal to "=" lies the logic of our function. The above code can also be written as below.
def add(a:Int, b:Int):Int={
println(a+b)
}
def sum(a:Int, b:Int):Int={
a+b
}
println(sum(10,20))
add(20,30)
Points to note
- Scala Functions start with a def keyword
- Scala permits nested function definitions
- Braces {} are optional. For clarity purposes once can enclose multi statement functions in braces.
- return statement is optional
- A Function that doesn't return any value can return Unit, equivalent to void in other languages.