Lesson 6 of 15
Functions
Functions
Functions in Scala are defined with def. The return type comes after : and the body after =:
def add(a: Int, b: Int): Int = a + b
println(add(3, 4)) // 7
For multi-statement bodies, use curly braces:
def greet(name: String): String = {
val message = "Hello, " + name
message + "!"
}
Default Parameters
Functions can have default values:
def power(base: Int, exp: Int = 2): Int = {
var result = 1
for (i <- 1 to exp) result *= base
return result
}
power(3) // 9 (uses default exp=2)
power(2, 10) // 1024
Your Task
Write a function area that takes width and height (both Int) and returns their product.
JS Transpiler loading...
Loading...
Click "Run" to execute your code.