Methods in Scala

In this part, we are going to talk about methods in Scala. As you dive into Scala, you'll find that there are lots of ways to define methods in Scala. We will demonstrate them in some of these ways:

def min(x1:Int, x2:Int) : Int = {
if (x1 < x2) x1 else x2
}

The preceding declaration of the method takes two variables and returns the smallest among them. In Scala, all the methods must start with the def keyword, which is then followed by a name for this method. Optionally, you can decide not to pass any parameters to the method or even decide not to return anything. You're probably wondering how the smallest value is returned, but we will get to this later. Also, in Scala, you can define methods without curly braces:

def min(x1:Int, x2:Int):Int= if (x1 < x2) x1 else x2

If your method has a small body, you can declare your method like this. Otherwise, it's preferred to use the curly braces in order to avoid confusion. As mentioned earlier, you can pass no parameters to the method if needed:

def getPiValue(): Double = 3.14159

A method with or without parentheses signals the absence or presence of a side effect. Moreover, it has a deep connection with the uniform access principle. Thus, you can also avoid the braces as follows:

def getValueOfPi : Double = 3.14159

There are also some methods which return the value by explicitly mentioning the return types. For example:

def sayHello(person :String) = "Hello " + person + "!"

It should be mentioned that the preceding code works due to the Scala compiler, which is able to infer the return type, just as with values and variables.

This will return Hello concatenated with the passed person name. For example:

scala> def sayHello(person :String) = "Hello " + person + "!"
sayHello: (person: String)String

scala> sayHello("Asif")
res2: String = Hello Asif!

scala>
..................Content has been hidden....................

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