Accepted answer

@Aavik please read How does yield work? article.

Desugared version of your example will look like:

case class Book(title: String, authors: List[String])

val books: List[Book] = List(
    Book(title = "kids watching", authors = List("Aavik","Arjun"))

books.flatMap { (book: Book) => 
  book.authors.withFilter { (name: String) =>
  }.map { _ =>

As you see map { _ => book.title } has the same scope as book variable. You can run this example in Scastie.

Ammonite REPL desugar can help to investigate how does Scala translate for-comprehensions.


if I got your question right, in the above example i.e

    book <- books
    name <- book.authors
    if name.startsWith("Aavik")
  } yield book.title

This will actually be converted to:

books.flatMap(((book) => book.authors.withFilter(((name) => name.startsWith("Aavik"))).map(((name) => book.title))))

So, as you can see we have book that is the input to the flatMap and it can be accessed anywhere inside it. So there is no issue in accessing book.title inside map as map is enclosed inside the flatMap.

Let me know if you want more clarity.

Related Query

More Query from same tag