Home
Scala
def Examples (Lambdas)
This page was last reviewed on Dec 15, 2023.
Dot Net Perls
Def. With def, a keyword in Scala 3.3, we define a function. We can specify a return type. And with lambda expressions, we use light, expression-based functions.
Syntax notes. We can place a def-function on a single line for a light, easy-to-read program. For more complex functions, multiple lines can be used.
Def example. Here we introduce 2 functions. We declare them in different ways. Both isImportant and isNotImportant return a Boolean.
Note The isImportant function receives an Int and returns a Boolean. It returns true if the argument size is greater than or equal to 10.
Note 2 The isNotImportant function uses a simpler syntax. Its return value (Boolean) is determined by the compiler.
Finally We invoke both functions. We print their result Booleans to the screen with println.
def isImportant(size: Int): Boolean = { // Return true if size is greater than or equal to 10. return size >= 10 } def isNotImportant(size: Int) = !isImportant(size) object Program { def main(args: Array[String]): Unit = { // Test the isImportant function. val result1 = isImportant(10) val result2 = isImportant(0) println(result1) println(result2) // Test the isNotImportant function. val result3 = isNotImportant(10) val result4 = isNotImportant(0) println(result3) println(result4) } }
true false false true
Lambda expressions. A lambda expression is a function that uses less syntax. It is often passed as argument, directly inline with the surrounding function call.
Note We use the map() function on the List to demonstrate lambdas. This function requires a function argument.
List
Note 2 We use the underscore variable (which is the argument passed to the lambda). We multiply that by 2 for the result.
Note 3 We use the expanded lambda expression syntax. The arrow symbol separates arguments from the return expression.
Tip Both lambda expressions syntax forms are equivalent. The underscore is just a shortcut.
object Program { def main(args: Array[String]): Unit = { val codes = List(100, 200, 300) println(codes) // Multiply all elements by 2. // ... Place in a new List. val multiplied = codes map (_ * 2) println(multiplied) // Multiply all elements by 3, using a longer syntax form. val multiplied2 = codes map (x => x * 3) println(multiplied2) } }
List(100, 200, 300) List(200, 400, 600) List(300, 600, 900)
Function syntax. Scala supports many variations of function call syntax. We can omit periods. We can omit parentheses. And we can use curly brackets for blocks.
Detail These too can use an underscore or an explicit argument. A type (like Int) can also be supplied.
object Program { def main(args: Array[String]): Unit = { val numbers = List(10) // One-element list. // Use no periods or parentheses. numbers foreach println _ // Use curly brackets. numbers foreach { println _ } // Use periods and parentheses. numbers.foreach(println(_)) // Use expanded lambda syntax. numbers.foreach(x => println(x)) // Use type in lambda syntax. numbers.foreach((x: Int) => println(x)) // Use curly brackets. numbers.foreach({ (x: Int) => println(x) }) } }
10 10 10 10 10 10
Unit. In Scala we use the Unit return type to indicate "no return value." This is a "void" function. The void keyword is not used.
Return An empty "return" statement can be used in a method that returns a Unit type. This means "no value."
Here The message() def prints a message to the screen based on its argument. It returns Unit—it is a void method.
// The Unit type is used to indicate "void" or no return value. def message(value: String): Unit = { println("Message: " + value) } object Program { def main(args: Array[String]): Unit = { // Call void method. message("cat") message("bird") } }
Message: cat Message: bird
Default arguments. We can specify a default value for arguments. Here we use a default value of "medium" for the size String argument in printSize.
Note We can avoid passing an argument when a default value is provided. We can call printSize with 0 or 1 arguments.
// Uses a default value of "medium" when no argument provided. def printSize(size: String = "medium") = println(size) object Program { def main(args: Array[String]): Unit = { // Print default size string. printSize() // Print specific strings. printSize("large") printSize("small") } }
medium large small
Repeated arguments. A def that receives a variable number of string arguments receives a "String*" type. Other types like "Int*" may also be used.
Note The argument type "String*" is not a list. But it can be looped over with a for-loop.
for, until
def addAllLengths(values: String*): Int = { // Add all string lengths in the string variable argument. var total = 0 for (v <- values) { total += v.length() } return total } object Program { def main(args: Array[String]): Unit = { // Use variable arguments. val result = addAllLengths("cat", "bird") println(result) } }
7
Many variations. Some languages use strict rules for correct programs. Other programs will not compile. Scala is more relaxed: we can omit periods, parentheses, brackets.
Many things can be thought of as functions. For example, the position of the stars in the sky is computed based on a function. In Scala we describe these actions with clear syntax.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 15, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.