What is Scala's yield?

前端 未结 9 900
忘掉有多难
忘掉有多难 2020-11-22 11:06

I understand Ruby and Python\'s yield. What does Scala\'s yield do?

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 11:33

    It is used in sequence comprehensions (like Python's list-comprehensions and generators, where you may use yield too).

    It is applied in combination with for and writes a new element into the resulting sequence.

    Simple example (from scala-lang)

    /** Turn command line arguments to uppercase */
    object Main {
      def main(args: Array[String]) {
        val res = for (a <- args) yield a.toUpperCase
        println("Arguments: " + res.toString)
      }
    }
    

    The corresponding expression in F# would be

    [ for a in args -> a.toUpperCase ]
    

    or

    from a in args select a.toUpperCase 
    

    in Linq.

    Ruby's yield has a different effect.

提交回复
热议问题