Scala – conversion from for-comprehension to map, flatMap


def getProduct(id: String): Try[Product]
def getPrice(product: Product): Try[Price]
def calculateProductPrice(product: Product, price: Price): Try[Price]

for {
  product <- getProduct("1234")
  price <- getPrice(product)
  calculatedPrice <- calculateProductPrice(product, price)
  if (calculatedPrice > 1000)
} yield (product, calculatedPrice)


getProduct("1234").flatMap{ product =>
  getPrice(product).flatMap{ price =>
    calculateProductPrice(product, price).filter { p => p > 1000 }
      .map{ p => (product, p) }
  }
}
    
Advertisements
This entry was posted in Programming, Scala and tagged . Bookmark the permalink.

2 Responses to Scala – conversion from for-comprehension to map, flatMap

  1. ysden123 says:

    In variant with for you check price (“if (price > 1000)”).
    In variant with map you check calculated price (“filter{p => p > 1000}”)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s