返回Future的方法出错[Option [BasicProfile]]

时间:2014-09-22 12:35:00

标签: scala securesocial

我正在使用SecureSocial(主版本)编写Play 2.3应用程序。 我已经创建了一个LoginUser,它代表了我系统中的用户数据。

/**
 * Class representing a User in the system.
 * @constructor Create a new LoginUser instance from a BasicProfile object.
 * @param profile represents the BasicProfile object associated with the user.
 */
case class LoginUser(val profile: BasicProfile)

现在我正在尝试实现UserService [T]特征(SecureSocial),但我遇到了麻烦。

/**
 * Class tha handle all the request for read/write user data in/from the database.
 */
class InMemoryUserService extends UserService[LoginUser] {

  private var tokens = Map[String, MailToken]()
  /**
   * Finds a user by provider id and user id.
   * @param providerId - the user provider id.
   * @param userId - the user user id.
   * @return an optional user
   */
  def find(providerId: String, userId: String): Future[Option[BasicProfile]] = {
    val future: Future[Option[LoginUser]] = UserServiceLogin.find(Json.obj("providerId" -> providerId, "userId" -> userId)).one
    future onComplete {
      case Success(Some(x)) => return x.profile
      case _ => None
    }
}

find方法返回Future [Option [BasicProfile]]对象,但编译器告诉我代码不正确。 这里是编译器的输出:

[error] /Users/alberto/git/recommendation-system/app/security/UserService.scala:68: type mismatch;
[error]  found   : securesocial.core.BasicProfile
[error]  required: scala.concurrent.Future[Option[securesocial.core.BasicProfile]]
[error]       case Success(Some(x)) => return x.profile

怎么了? 我怎样才能解决我的问题?

1 个答案:

答案 0 :(得分:4)

您不应通过FutureonComplete上注册回调。相反,您希望map内容更改类型:

def find(providerId: String, userId: String): Future[Option[BasicProfile]] = {
    val future: Future[Option[LoginUser]] = UserServiceLogin.find(Json.obj("providerId" -> providerId, "userId" -> userId)).one

    future map {
      case Some(x) => Some(x.profile)
      case None => None
    }
}

这应该让编译开心:)注意onComplete的返回类型是Unit,而使用map我可以对{{1}的内容应用任何更改}}

Future mapFuture的{​​{1}}一个不那么冗长的版本:

Option