
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Type Patterns
- Scala - Exception Handling
- Scala - Extractors
- Scala - Regular Expressions
- Scala Files I/O
- Scala - Files I/O
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala - BDD Testing
Scala - Yield Keyword
You can store return values from a "for" loop in a variable or can return through a function. To do so, you prefix the body of the 'for' expression by the keyword yield.
Syntax
The following is the syntax to use yield keyword −
var retVal = for { var x <- List if condition1 if condition2 ... } yield x
Note − the curly braces have been used to keep the variables and conditions and retVal is a variable where all the values of x will be stored in the form of collection.
Example of Scala Yield Keyword
Try the following example program to understand loop with yield −
object Demo { def main(args: Array[String]) { var a = 0 val numList = List(1,2,3,4,5,6,7,8,9,10) // for loop execution with a yield var retVal = for { a <- numList if a != 3 if a < 8 } yield a // Now print returned values using another loop. for (a <- retVal) { println("Value of a: " + a) } } }
In the above example, we have first filtered the element using condition a != 3; and a < 8. So it will select only elements that are not equal to 3 and are less than 8. Now, yield keyword is used to collect the selected elements into a new list retVal. The second for loop iterates over retVal and prints each element.
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
value of a: 1 value of a: 2 value of a: 4 value of a: 5 value of a: 6 value of a: 7
Doubling Elements Using Yield Keyword
Use yield to double each element in a list −
object DoubleDemo { def main(args: Array[String]) = { val numbers = List(1, 2, 3, 4, 5) val doubled = for (n <- numbers) yield n * 2 println(doubled) // Output: List(2, 4, 6, 8, 10) } }
In this example, the yield keyword takes each element n from numbers, doubles it (n * 2), and collects the results into a new list doubled.
Save the above program in DoubleDemo.scala. The following commands are used to compile and execute this program.
Command
\>scalac DoubleDemo.scala \>scala DoubleDemo
Output
List(2, 4, 6, 8, 10)
Creating pairs from two lists and computing their products.
object ProductDemo { def main(args: Array[String]) = { val list1 = List(1, 2, 3) val list2 = List(4, 5, 6) val products = for { a <- list1 b <- list2 } yield a * b println(products) // Output: List(4, 5, 6, 8, 10, 12, 12, 15, 18) } }
In this example, for each element a from list1 and each element b from list2, their product a * b is computed and collected into the products list.
Save the above program in ProductDemo.scala. The following commands are used to compile and execute this program.
Command
\>scalac ProductDemo.scala \>scala ProductDemo
Output
List(4, 5, 6, 8, 10, 12, 12, 15, 18)