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}
Functions need not have parameters or return values:
def helloWorld = println("Hello, World!")
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}
Functions can have as many parameters as required.
def helloWorld(times: Int) = { for (i <- 0 until times) { println("Hello, World!"); } }
And as always, functions can return a value after evaluation.
In the below example, helloWorld
returns an IndexedSeq
containing as many "Hello, World!" as required.
def helloWorld(times: Int): IndexedSeq[String] = { for (i <- 0 until times) yield { "Hello, World!" }}