类型 Future.pdfVIP

  • 1
  • 0
  • 约8.26千字
  • 约 7页
  • 2018-03-06 发布于湖北
  • 举报
类型 Future

类型 Future 作为⼀个对 Scala 充满热情的开发者,你应该已经听说过 Scala 处理并发的能⼒,或许 你就是 这个吸引来的。相较于⼤多数编程语⾔低级的并发 API ,Scala 提供的⽅法可 以让⼈们更好的理解并发以及编写良构的并发程序。 本章的主题- Future 就是这种⽅法的两⼤基⽯之⼀。 (另⼀个是 actor )我会解释 Future 的优点,以及它的函数式特征。 如果你想动⼿试试接下来的例⼦,请确保 Scala 版本不低于 2.9.3 ,Future 在 2.10 .0 版 本中引⼊,并向后兼容到 2.9.3 ,最初,它是 Akka 库的⼀部分 (API略有不同)。 顺序代码为什么会变坏 假设你想准备⼀杯卡布奇诺,你可以⼀个接⼀个的执⾏以下步骤: 1. 研磨所需的咖啡⾖ 2. 加热⼀些⽔ 3. ⽤研磨好的咖啡⾖和热⽔制做⼀杯咖啡 4 . 打奶泡 5. 结合咖啡和奶泡做成卡布奇诺 转换成 Scala 代码,可能会是这样: import scala.util.Try // Some type aliases, just for getting more meaningful method sign type CoffeeBeans = String type GroundCoffee = String case class Water temperature: Int) type Milk = String type FrothedMilk = String type Espresso = String type Cappuccino = String // dummy implementations of the individual steps: def grind beans: CoffeeBeans): GroundCoffee = sground coffee of $ def heatWater water: Water): Water ` water.copy temperature ` 85) def frothMilk milk: Milk): FrothedMilk = sfrothed $milk def brew coffee: GroundCoffee, heatedWater: Water): Espresso = es def combine espresso: Espresso, frothedMilk: FrothedMilk): Cappucc // some exceptions for things that might go wrong in the individua // well need some of them later, use the others when experimenti case class GrindingException msg: String) extends Exception msg) case class FrothingException msg: String) extends Exception msg) case class WaterBoilingException msg: String) extends Exception ms case class BrewingException msg: String) extends Exception msg) // going through these steps sequentially : def prepareCappuccino ): Try[Cappuccino] = for { ground - Try grind arabica beans)) water - Try heatWater Water 25))) espresso - Try brew ground, water)) foam - Try frothMilk milk)) } yield combine espresso, foam) 这样做有⼏个优点:可以很轻易的弄清楚事情的步骤,⼀⽬了然,⽽且不会混淆。 (毕竟没有上下⽂切换)不好的⼀⾯是,⼤部分时间,你的⼤脑和⾝体都处于等待的 状态:在等待研磨咖啡⾖时,你完全不能做任何事情,只有当这⼀步完成后,你才能 开始烧⽔。这显然是在浪费时间,所以你可能想⼀次开始多个步骤,让它们同时执 ⾏,⼀旦⽔烧开,咖啡⾖也磨好了,你可以

文档评论(0)

1亿VIP精品文档

相关文档