Method

 In Scala methods are defined like this:
def add(x:Int,y:Int) :Int={
            x+y
}

When a method body comprises a single expression which is less than 30 (or so) characters, it should be given on a single line with the method:
def add(a: Int, b: Int): Int = a + b
 
Here we defined an add method with the def keyword. It took two Int as an input and returned an Int. Both inputs are immutable (in the sense that they are managed just like if they were declared as val).The return keyword is optional. The method will automatically return the last expression. Moreover, it’s worth mentioning that in Scala (compared to Java), return exits the current method, not the current block. One last thing to add, the return type is optional. The Scala compiler is also able to infer it. Yet, for the sake of code maintainability, it might be a good option to set it explicitly.

A method without output can be written is both ways:

def printSomething(s: String) = {
   println(s)
}

def printSomething(s: String): Unit = {
  println(s)
}

We can also return multiple outputs like this:

def increment(x: Int, y: Int): (Int, Int) = {
  (x + 1, y + 1)
}

Let’s consider a bar method without arguments. We can call this method in both ways:

def foo(): Unit = {
  bar()
  bar


Also, Scala allows us to indicate that a method argument can be repeated. Just like in Java, this repeatable argument must be the last parameter:

def variablesArguments(args: Int*): Int = {
  var n = 0
  for (arg <- args) {
    n += arg
  }
  n
}

we can also define default parameters value:

def default(x: Int = 2, y: Int): Int = {
  x * y
}

class MyClass {
  var myField = 0;

  def getMyField() : Int = {
    return this.myField;
  }
}

The above example defines a method called getMyField. The return type, Int, is declared after the method name. Inside the { and } the method body is declared. The method currently just returns the myField field. Notice the = sign between the Int and {. Methods that return a value should have this equals sign there.

Here is a method that doesn't return anything, but instead modifies the internal state (field) of the object. Notice how this addToMyField() method does not have the equals sign, and no return type specified.

    class MyClass {
      var myField = 0;

      def getMyField() : Int = {
        return this.myField;
      }
  
         def addToMyField(value : Int) {
         this.myField += value;
         }
       }


Method Invocation

Method Invocation is a technique which demonstrate different synatx in which we dynamically call methods of a class with an object. The naming conventions of Scala are same as of Java.    
obj.display(“name”)
obj.display(“name”, 22)
class x
{
    def display(str: String)
    {
        println(str)
    }
}
object main
{
    def main(args: Array[String])
    {
        val obj = new x
        obj.display("student")
    }
}

No comments:

Post a Comment