Scala用于理解期货和期权
发布时间:2020-12-16 18:39:47 所属栏目:安全 来源:网络整理
导读:我最近阅读了Manuel Bernhardt的新书 Reactive Web Applications.在他的书中,他指出Scala开发人员不应该使用.get来检索可选值. 我想接受他的建议,但我正在努力避免.get用于对期货的理解. 假设我有以下代码: for { avatarUrl - avatarService.retrieve(email
我最近阅读了Manuel Bernhardt的新书
Reactive Web Applications.在他的书中,他指出Scala开发人员不应该使用.get来检索可选值.
我想接受他的建议,但我正在努力避免.get用于对期货的理解. 假设我有以下代码: for { avatarUrl <- avatarService.retrieve(email) user <- accountService.save(Account(profiles = List(profile.copy(avatarUrl = avatarUrl))) userId <- user.id _ <- accountTokenService.save(AccountToken.create(userId,email)) } yield { Logger.info("Foo bar") } 通常,我会使用AccountToken.create(user.id.get,email)而不是AccountToken.create(userId,email).但是,当试图避免这种不良做法时,我得到以下异常: [error] found : Option[Nothing] [error] required: scala.concurrent.Future[?] [error] userId <- user.id [error] ^ 我怎么解决这个问题? 解决方法
第一种选择
如果你真的想要用于理解,你必须将它分成几个fors,其中每个都使用相同的monad类型: for { avatarUrl <- avatarService.retrieve(email) user <- accountService.save(Account(profiles = List(profile.copy(avatarUrl = avatarUrl))) } yield for { userId <- user.id } yield for { _ <- accountTokenService.save(AccountToken.create(userId,email)) } 第二种选择 另一个选择是完全避免Future [Option [T]]并使用Future [T],它可以实现为Failure(e),其中e是NoSuchElementException,只要你期望None(在你的情况下,是accountService.save()方法) : def saveWithoutOption(account: Account): Future[User] = { this.save(account) map { userOpt => userOpt.getOrElse(throw new NoSuchElementException) } } 然后你会有: (for { avatarUrl <- avatarService.retrieve(email) user <- accountService.saveWithoutOption(Account(profiles = List(profile.copy(avatarUrl = avatarUrl))) _ <- accountTokenService.save(AccountToken.create(user.id,email)) } yield { Logger.info("Foo bar") }) recover { case t: NoSuchElementException => Logger.error("boo") } 第三种选择 回到map / flatMap并介绍中间结果. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |