The return in Scala

Before learning how a Scala method returns a value, let's recap the structure of a method in Scala:

def functionName ([list of parameters]) : [return type] = {
function body
value_to_return
}

For the preceding syntax, the return type could be any valid Scala data type and a list of parameters will be a list of variables separated by a comma and a list of parameters and return type is optional. Now, let's define a method that adds two positive integers and returns the result, which is also an integer value:

scala> def addInt( x:Int, y:Int ) : Int = {
| var sum:Int = 0
| sum = x + y
| sum
| }
addInt: (x: Int, y: Int)Int

scala> addInt(20, 34)
res3: Int = 54

scala>

If you now call the preceding method from the main() method with the real values, such as addInt(10, 30), the method will return an integer value sum, which is equal to 40. As using the keyword return is optional, the Scala compiler is designed such that the last assignment will be returned with the absence of the return keyword. As in this situation, the greater value will be returned:

scala> def max(x1 : Int , x2: Int)  = {
| if (x1>x2) x1 else x2
| }
max: (x1: Int, x2: Int)Int

scala> max(12, 27)
res4: Int = 27

scala>

Well done! We have seen how to use variables and how to declare a method in Scala REPL. Now, its time to see how to encapsulate them inside Scala methods and classes. The next section discusses Scala objects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.6.10