传入来自Option Future的Int值

时间:2017-03-13 21:12:37

标签: scala

我有一个我正在努力的方法,它有一个选项[未来[用户]]。

case class Employee(..., userId: Option[Int], ...)

现在我遇到的问题是Employee案例类采用可选的UserId值:

mylabel = gtk.Label()
mylabel.set_markup("<span foreground = 'italic', style = 'italic'>Blue text</span>")

print mylabel.get_markup() # i know this method not exist

#output: <span foreground = 'italic', style = 'italic'>Blue text</span>

如果它存在,我如何将user.id值传递给Employee案例类?

2 个答案:

答案 0 :(得分:1)

你可以使用Service Locator

做一个小技巧
Option[Future[Int]]

答案 1 :(得分:1)

您需要一些逻辑来将您的类型转换为您想要的东西:

val userOptFut: Option[Future[User]] = ???

// Convert the Option[Future[User]] to a Option[Future[Int]]
val maybeFutureID = userOptFut.map(_.map(_.id))

// Convert the Option[Future[Int]] to a Future[Option[Int]]
val futureOptionID = maybeFutureID match {
  case None => Future.successful(Option.empty[Int])
  case Some(futureID) => futureID.map(id => Some(id))
}

for {

  // Wait for Future[Option[Int]]
  maybeID <- futureOptionID

  // Insert employee
  employee <- employeeDao.insert(Employee(..., maybeID, ...))
} yield ...