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

后端 未结 5 1845
南笙
南笙 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:31

    Another great use of for-comprehension is for internal DSL. ScalaQL is a great example of this. It can turn this

    val underAge = for { 
      p <- Person 
      c <- Company 
      if p.company is c 
      if p.age < 14 
    } yield p 
    

    into this

    SELECT p.* FROM people p JOIN companies c ON p.company_id = c.id WHERE p.age < 14 
    

    and a whole lot more.

提交回复
热议问题