Welcome back to the Scala tutorial.
This post is the continuation of A Simple Tutorial on Scala – Part – 1
In the Part-1 we learned the following topics on Scala
- Scala Features
- Variables and Methods
- Condition and Loops
- Variables and Type Inference
- Classes and Objects
Keeping up the same pace, we will learn the following topics in the 2nd part of the Scala series.
- Functions Representation
- Collections
- Sequence and Sets
- Tuples and Maps
- Higher Order Functions
- Build Tool – SBT
Functions Representation
We have already discussed functions. We can write a function in different styles in Scala. The first style is the usual way of defining a function.
scala> def add(x : int, y : int) : Int = { return x + y }
Please note that the return type is specified as Int.
In the second style, please note that the return type is omitted, also there is no “return” keyword. The Scala compiler will infer the return type of the function in this case.
scala> def add(x : int, y : int) = { //return type is inferred x + y //"return" keyword is optional }
If the function body has just one statement, then the curly braces are optional. In the third style, please note that there are no curly braces.
def add(x : Int, y : Int) = x + y