美文网首页
scala中yield关键字

scala中yield关键字

作者: 大道至简_6a43 | 来源:发表于2020-02-26 21:33 被阅读0次

    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 = ()

    相关文章

      网友评论

          本文标题:scala中yield关键字

          本文链接:https://www.haomeiwen.com/subject/zhhgchtx.html