1.yield作用
当我们使用for或者if,或者for与if联合使用,会过滤出符合你条件的集合,但是当你并不需要打印过滤出来的集合时,
你需要对过滤后的集合进行处理,使用yield关键字可以在for表达式中生成新的集合。
2.yield例子
2.1有yield关键字
val fruits = List("banana fruit","apple fruit","peach","grapes","pear")
val filterFruit = for {
fruit <- fruits
if fruit.contains("fruit") && !fruit.startsWith("banana")
}yield fruit
结果为:
fruits: List[String] = List(banana fruit, apple fruit, peach, grapes, pear)
filterFruit: List[String] = List(apple fruit)
我们看到没有打印出过滤后的集合。
2.2没有yield关键字
val fruits = List("banana fruit","apple fruit","peach","grapes","pear")
val filterFruit = for {
fruit <- fruits
if fruit.contains("fruit") && !fruit.startsWith("banana")
} fruit
结果为:
fruits: List[String] = List(banana fruit, apple fruit, peach, grapes, pear)
filterFruit: Unit = ()
2.3带println关键字
val fruits = List("banana fruit","apple fruit","peach","grapes","pear")
val filterFruit = for {
fruit <- fruits
if fruit.contains("fruit") && !fruit.startsWith("banana")
} println(fruit)
结果为:
fruits: List[String] = List(banana fruit, apple fruit, peach, grapes, pear)
apple fruit
filterFruit: Unit = ()
网友评论