斯卡拉 |产量关键字
yield关键字将在循环迭代完成后返回结果。 for 循环在内部使用缓冲区来存储迭代结果,当完成所有迭代时,它会从该缓冲区产生最终结果。它不像命令式循环那样工作。返回的集合的类型与我们倾向于迭代的类型相同,因此 Map 产生一个 Map,一个 List 产生一个 List,依此类推。
句法:
var result = for{ var x Note: The curly braces have been used to keep the variables and conditions and result is a variable wherever all the values of x are kept within the form of collection.Example:// Scala program to illustrate yield keyword // Creating objectobject GFG { // Main method def main(args: Array[String]) { // Using yield with for var print = for( i <- 1 to 10) yield i for(j<-print) { // Printing result println(j) } } } Output:1
2
3
4
5
6
7
8
9
10In above example, the for loop used with a yield statement actually creates a sequence of list.Example:// Scala program to illustrate yield keyword // Creating objectobject GFG { // Main method def main(args: Array[String]) { val a = Array( 8, 3, 1, 6, 4, 5) // Using yield with for var print=for (e <- a if e > 4) yield e for(i<-print) { // Printing result println(i) } } } Output:8
6
5In above example, the for loop used with a yield statement actually creates a array. Because we said yield e, it’s a Array[n1, n2, n3, ....]. e is our generator and if (e > 4) could be a guard that filters out number those don't seem to be greater than 4.