Scala's for-comprehensions: vital feature or syntactic sugar?

后端 未结 5 1796
南笙
南笙 2021-01-31 20:04

When I first started looking at Scala, I liked the look of for-comprehensions. They seemed to be a bit like the foreach loops I was used to from Java 5, but with functional rest

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-31 20:25

    In some cases, for comprehensions can express intent better, so when they do, use them.

    Also note that with for comprehensions, you get pattern matching for free. For example, iterating over a Map is much simpler with for comprehension:

    for ((key, value) <- map) println (key + "-->" + value)

    than with foreach:

    map foreach { case (key, value) => println (key + "-->" + value) }

提交回复
热议问题