定义
一般scala中yield和for循环一起使用,基于原始集合返回一个新可迭代集合,官方文档说明如下
Using yield after for is the “secret sauce” that says, “I want to yield a new collection from the existing collection that I’m iterating over in the for-expression, using the algorithm shown.”
使用
val names = List("_adam", "_david", "_frank")
println{ //打印返回的集合
for(i <- 0 to names.length-1) yield i+names(i)
}
println{
for(name <- names) yield { name.drop(1).capitalize }
}
打印结果如下
Vector(0_adam, 1_david, 2_frank)
List(Adam, David, Frank)