Title here
Summary here
Functions are central in Scala. We’ll learn about functions with a few different examples.
object Functions {
// Here's a function that takes two Ints and returns
// their sum as an Int.
def plus(a: Int, b: Int): Int = {
// Scala allows implicit returns, so the last expression
// in a function is automatically returned.
a + b
}
// In Scala, you can omit curly braces for single-expression functions
def plusPlus(a: Int, b: Int, c: Int): Int = a + b + c
def main(args: Array[String]): Unit = {
// Call a function just as you'd expect, with
// name(args).
val res = plus(1, 2)
println(s"1+2 = $res")
val res2 = plusPlus(1, 2, 3)
println(s"1+2+3 = $res2")
}
}
To run the program:
$ scala Functions.scala
1+2 = 3
1+2+3 = 6
There are several other features to Scala functions. One is multiple return values, which we’ll look at next.
Key differences from the original code:
object
instead of package
for top-level definitions.def
in Scala.:
to separate parameter names from their types, and =>
to separate the parameter list from the function body for single-expression functions.return
keyword is often omitted.println
is used instead of fmt.Println
.s"..."
syntax.main
function in Scala takes an Array[String]
as an argument and has a return type of Unit
.These changes reflect idiomatic Scala while maintaining the structure and purpose of the original example.