Querying a Collection Using For-Comprehensions in Scala

Extracting elements from a collection of objects using Scala's for-comprehensions.
// Defining a case class
case class Book(title: String, author: List[String])

// Creating Book instances
val book1: Book = Book("War & Peace", List("Leo Tolstoy"))
val book2: Book = Book("Crime & Punishment", List("Fyodor Dostoievski"))
val book3: Book = Book("Rebecca", List("Daphne du Maurier"))
val book4: Book = Book("Les Miserables", List("Victor Hugo"))
val book5: Book = Book("The Count of Monte Cristo", List("Charles Dumas"))
val book6: Book = Book("The Passion According to G.H.", List("Clarice Lispector"))
val book7: Book = Book("Ham on Rye", List("Charles Bukowski"))
val book8: Book = Book("The Brothers Karamazov", List("Fyodor Dostoievski"))

// Defining a list of books
val myBooks: List[Book] = List(book1, book2, book3, book4, book5, book6, book7, book8)

// Getting all books starting with "The"
for
    b <- myBooks
    if b.title.startsWith("The")
yield b.title

// res0: List[String] = List(The Count of Monte Cristo, The Passion According to G.H., The Brothers Karamazov)
Scala
Markdown is a lightweight markup language used for creating formatted text. It was created in 2004 by John Gruber &…
In our previous article, What Is Julia, and Why It Matters?, we discussed why Julia is so relevant today and…
A filesystem is a method and data structure used by operating systems to manage how data is stored, organized and retrieved….
Regular Expressions, also known as RegEx, is a pattern-matching tool used to find patterns in strings. We can think…

Request Full Resume