Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

<< Back to SCALA

Scala Def: return Unit and Lambdas

Use the def keyword and a Unit return type. A lambda is passed an argument to another function.
Def, functions. A function takes an action. It returns a value. It might us tell whether something is important or not. This involves some logic to test arguments.
With def, a keyword in Scala, we define a function. We can specify a return type. And with lambda expressions, we use light, expression-based functions.
Def example. Here we introduce 2 functions. We declare them in different ways. Both isImportant and isNotImportant return a Boolean.

First: The isImportant function receives an Int and returns a Boolean. It returns true if the argument size is greater than or equal to 10.

Second: 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.

Scala program that uses def, functions 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) // 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) Output 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.

Map: We use the map() function on the List to demonstrate lambdas. This function requires a function argument.


First: We use the underscore variable (which is the argument passed to the lambda). We multiply that by 2 for the result.

Second: 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.

Scala program that uses lambda expressions 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) Output 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.

Lambdas: These too can use an underscore or an explicit argument. A type (like Int) can also be supplied.

Scala program that shows function syntax variations 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) }) Output 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.

Scala program that uses Unit return type // The Unit type is used to indicate "void" or no return value. def message(value: String): Unit = { println("Message: " + value) } // Call void method. message("cat") message("bird") Output 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.

Scala program that uses default argument // Uses a default value of "medium" when no argument provided. def printSize(size: String = "medium") = println(size) // Print default size string. printSize() // Print specific strings. printSize("large") printSize("small") Output 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.

Scala program that uses variable-length arguments 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 } // Use variable arguments. val result = addAllLengths("cat", "bird") println(result) Output 7
Repeated arguments, research. For an optimal understanding of Scala, reading the language specification is necessary. Variable-length arguments are scala.Seq instances.

Quote: The last value parameter of a parameter section may be suffixed by "*". The type of such a repeated parameter inside the method is then the sequence type scala.Seq[T].

Basic Declarations:
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.
A review. 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.
The Dev Codes