Scala Functions: Examples and Reference

Scala Functions: Examples and Reference

Last updated:

Here are some of the ways you can define and/or create functions in Scala:

Simplest possible way

For functions which are only one line long.

def func1(a:Int,b:Int) = 

Functions with longer bodies

def func2(a:Int) = {
    val foo = "bar"
    val bar = "foo"
    // return value
    a * 2

Assign a function to a variable

After you assign a function to a variable, you can call the apply method on that variable (that is, use it as if it were a function)

P.S.:Note that what actually gets assigned to the variable is an anonymous function - a function with no name, just a body.

val func3 = (a:Int, b:Int) =>
    a + b

likewise, for longer functions:

val func4 = (a:Int, b:Int) => {
    val sum = a + b
    val average = sum / 2

Recursive functions

Recursive functions require that you explicitly set their return type:

def factorial(n:Int) :Int = { //explicit return type needed or you'll get an Error
    if (n == 0) 1
    else n*factorial(n-1)

Functions that take other functions as parameters

Functions in Scala can take other functions as parameters (and also return functions as the result of a Function).

// can you guess what this will do?
def applyToAll( func: Char => Char , str: String) = {

applyToAll( c => c.toUpper, "foobarbaz")
// returns "FOOBARBAZ"

OBS.: There were tested against Scala 2.10.4