Functions and methods in Scala

Functions and methods are fundamental concepts in programming, and Scala supports both of them. Here’s a brief overview of functions and methods in Scala:

1. Functions: Functions in Scala are defined using the “def” keyword and can take zero or more parameters. Here’s an example:

``
   def add(x: Int, y: Int): Int = {
       x + y
   }
   println(add(2, 3)) // prints 5
   

`

In this example, “add” is a function that takes two integer parameters and returns their sum. The function is declared using the “def” keyword, and the return type is specified after the parameter list.

2. Methods: Methods in Scala are similar to functions, but they are associated with a class or object. Here’s an example:

``
   class MyClass {
       def add(x: Int, y: Int): Int = {
           x + y
       }
   }
   val obj = new MyClass()
   println(obj.add(2, 3)) // prints 5
   

`

In this example, “add” is a method that is defined inside the “MyClass” class. To call the method, you first need to create an instance of the class using the “new” keyword, and then call the method on the instance.

3. Anonymous functions: Scala also supports anonymous functions, which are functions that don’t have a name and are definedinline. Here’s an example:

``
   val add = (x: Int, y: Int) => x + y
   println(add(2, 3)) // prints 5
   

`

In this example, “add” is an anonymous function that takes two integer parameters and returns their sum. The function is defined using the “=>” operator, which is known as the “fat arrow” operator.

4. Higher-order functions: Scala also supports higher-order functions, which are functions that take other functions as parameters or return functions as results. Here’s an example:

``
   def applyFunction(f: Int => Int, x: Int): Int = {
       f(x)
   }
   val result = applyFunction(x => x * 2, 3)
   println(result) // prints 6
   

`

In this example, “applyFunction” is a higher-order function that takes a function “f” and an integer “x” as parameters. The function “f” is applied to “x” and the result is returned. The “x => x * 2” is an anonymous function that takes an integer “x” and returns its double.

Scala’s support for functions and methods makes it a powerful and flexible language that can be used for a wide range of applications.