Reading — step 1 of 6
Learn
~1 min readFunctions
Define a method with def:
def square(n: Int): Int = n * n
def greet(name: String, greeting: String = "Hello"): String =
s"$greeting, $name!"
The last expression is the return value. Explicit return exists but is rarely used (and discouraged).
Multi-statement bodies use braces:
def factorial(n: Int): Int = {
var result = 1
for (i <- 1 to n) result *= i
result
}
Function values (anonymous functions) use =>:
val double = (n: Int) => n * 2
val add = (a: Int, b: Int) => a + b
double(5) // 10
add(3, 4) // 7
Difference between def (method) and val ... => (function value): mostly transparent — in most contexts they're interchangeable. Functions are first-class values.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…