Jwan622
Jwan622

Reputation: 11639

for block in scala with a yield

Where is this documented in the Odersky book:

def bestBuyerPrice: Option[Price] = bids.headOption

for {
   price1 <- bestBuyerPrice
   price2 <- bestAskerPrice
} yield (price1.price + price2.price) / 2

What is this syntax called? Where is this documented?

What is the generator for? Isn't bestBuyerPrice either None or Some?

Upvotes: 1

Views: 1505

Answers (2)

Tim
Tim

Reputation: 27356

There are two things going on here.

Firstly, as already observed, using for is just a shorthand for calling map and flatMap on a collection. A key thing to note is that the type of the collection returned by for is the type of the collection in the first <- line.

Secondly, you can treat an Option value as if it were a collection with 0 or 1 elements. Calling map on an Option will return None if the option is None, or Some(y) if the option is Some(x). Calling flatMap on a collection of Options will remove all the None values from the collection and extract the value of all the Some options.

So putting this together, your code returns an Option because bestBuyerPrice is an option. If either bestBuyerPrice or bestAskerPrice is None then the result is None because that is what map/flatMap returns. If they are both Some(x) then the result is Some(y) where y is result of the yield.

Upvotes: 3

GClaramunt
GClaramunt

Reputation: 3158

I don't have the latest edition of the book, but look for "for comprehensions", essentially is syntactic sugar for chaining flatMaps and map.

See https://docs.scala-lang.org/tour/for-comprehensions.html

Upvotes: 2

Related Questions