Parameters and Return Types
In this page:
Parameters and Return Types
Parameters are declared with a name and type, like (name: String, age: Int), and the return type follows the parameter list after a colon. Scala can often infer the return type from the body, but explicit return types are recommended for public methods since they document intent and prevent surprising inference results. The last expression in the body is automatically the return value -- an explicit return is rarely used in idiomatic Scala.
Note: Explicit return statements are considered unidiomatic in Scala outside of early-exit edge cases -- let the last expression be the return value instead.
Example: Parameters and Return Types
object Main extends App {
def add(a: Int, b: Int): Int = {
a + b
}
val result = add(3, 4)
println(result)
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: