Functions in Scala

In Scala 2, every class / object can contain its own methods. In Scala 3, these methods can exist outside objects and classes and are called functions.

Functions in programming are like functions in math. They evaluate an expression and return a result.Functions are normally used to break large programs into smaller modules and improve reusability.

The syntax of a simple function / method looks like this:

def methodName(param1: Type1, param2: Type2): ReturnType = {  // function body}

The following are some example functions:

With No Parameters And No Returned Value

def helloWorld() = println("Hello, World!")

With No Parameters And A Returned Value

You can return a value from the function either through an expression or by explicitly using the return keyword.

def helloWorld(): String = "Hello, World!"
def giveMeOne(): Int = {  return 1;}

With Parameters And No Returned Value

Functions can have as many parameters as required.

 def helloWorld(times: Int) = {   for (i <- 0 until times) yield {     println("Hello, World!");   } }

With Parameters And A Returned Value

def helloWorld(times: Int): IndexedSeq[String] = { for (i <- 0 until times) yield {   "Hello, World!" }}