Last Updated: August 05, 2016
·
456
· ahmad_ragab

Scala For Comprehensions are Their Own Reward

val one = "This checks for scala or sbt patterns"
val two = "java rocks"
val sentences = List(one, two)
val dict = List("scala", "sbt", "patterns")

val result = for {
    sentence <- sentences
    does = dict forall sentence.contains
} yield (sentence, does)

//result: List[(String, Boolean)] = List((This checks for scala or sbt patterns,true), (java rocks,false))

Given a list of sentences the comprehension checks to see if every word in a dictionary (list) appears in each sentence and returns a list of pairs containing the sentence and the result.

For comprehensions are really powerful, and useful applications of functional programming concepts such as map and flatMap, in a sugared expressive style. One of the many reasons Scala is such an interesting and fun language to use.

This is a good post that describes the idiomatic applications of the for comprehension in Scala.

2 Responses
Add your response

Somehow I have never become interested in Scala, despite it being so functional and having a number of interesting and strong sides, like you've indicated. Regardless, thanks Ahmad for showing this.

Btw. the link to the article at nerd.kelseyinnis.com seems to be broken. Just saying.

over 1 year ago ·

Thank you for the comment. If TIOBE Indexes are to be believed you are almost certainly in the majority. Also, thanks for the heads-up about the link, it seems to be a common error on coderwall.

over 1 year ago ·