Parameters and Return Types
Parameters are the blanks a function asks you to fill, each with a kind, and the return type says what kind of answer comes back. It is like an order form with the type of thing to put in each blank.
In this page:
Syntax
def function_name(name: String, age: Int): ReturnType = {
// body
result
}
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting to give parameter types, as in
def add(a, b), which does not compile. - Writing
return a + bin a simple function when the last expression is already returned. - Declaring
: Intbut the last expression returns aString, which gives a type mismatch error.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: