avatar

Andres Jaimes

Examples of ‘for’ queries with Scala

By Andres Jaimes

On this page you are going to find some examples of ‘for’ queries.
Let’s start by defining the following database:

 1case class Book(title: String, authors: List[String])
 2
 3val books: List[Book] = List(
 4  Book("structure and interpretation of computer programs",
 5      List("abelson, harald", "sussman, gerald j.")),
 6  Book("introduction to functional programming",
 7    List("bird, richard", "wadler, phil")),
 8  Book("effective java",
 9    List("bloch, joshua")),
10  Book("java puzzlers",
11    List("bloch, joshua", "gafter, neal")),
12  Book("programming in scala",
13    List("odersky, martin", "spoon, lex", "venners, bill"))
14)

Find the titles of books whose author’s name is ‘bird’

1for {
2  b <- books
3  a <- b.authors
4  if a startsWith "bird"
5} println(a)

prints

bird, richard

Find all the books which have the work ‘program’ in the title

1for {
2  b <- books
3  if b.title contains "program"
4} println(b)

prints

Book(structure and interpretation of computer programs,List(abelson, harald, sussman, gerald j.))
Book(introduction to functional programming,List(bird, richard, wadler, phil))
Book(programming in scala,List(odersky, martin, spoon, lex, venners, bill))

Find the names of all authors who have written at least two books present in the database

 1val authors = {
 2  for {
 3    b1 <- books
 4    b2 <- books
 5    if b1 != b2
 6    a1 <- b1.authors
 7    if b2.authors.contains(a1)
 8  } yield a1
 9}.distinct
10
11println(authors)

prints

List(bloch, joshua)

Happy coding.