Scala Functions

Defining and using functions in Scala

Basic Function

def greet(): Unit = { # function without parameters
    println("Hello")
}

Function with Parameters

def greet(name: String): Unit = { # function with parameter
    println(s"Hello, $name")
}

Return Values

def add(a: Int, b: Int): Int = { # explicit return type
    a + b # implicit return (last expression)
}
def multiply(a: Int, b: Int) = a * b # single-expression

Default Parameters

def greet(name: String = "Guest"): Unit = { # default parameter
    println(s"Hello, $name")
}
greet() # uses default "Guest"

Anonymous Functions

val add = (a: Int, b: Int) => a + b # lambda function
val double = (x: Int) => x * 2
list.map(x => x * 2) # inline lambda
list.map(_ * 2) # underscore notation

Currying

def add(a: Int)(b: Int): Int = a + b # curried function
val add5 = add(5)_ # partial application
add5(3) # returns 8