Scala:如何隐式传递类隐式实例的属性?

时间:2016-09-18 13:37:41

标签: scala implicit

我有以下代码:

object Application {

  case class User(id: Long, username: String)
  case class Request(path: String)
  case class WrappedRequest(user: User, request: Request)

  def updateUserAction(implicit request: WrappedRequest) = {
    updateUser("john@mail.com") // <-- I need request.user to be passed implicitly here
  }

  def updateUser(email: String)(implicit user: User) = {
     println(user.username)
  }


  def main(args: Array[String]) = {
    implicit val request = WrappedRequest(User(1L, "john"), Request("/"))
    updateUserAction
  }

}

从上面可以隐式地将 updateUserAction 方法中的 request.user 传递给 updateUser 方法吗?

2 个答案:

答案 0 :(得分:5)

进行从WrappedRequestUser的隐式转换,以便所有需要WrappedRequest的方法都可以访问隐式User

implicit def req2User(implicit request: WrappedRequest): User = request.user

答案 1 :(得分:2)

喜欢这个吗?

def updateUserAction(implicit request: WrappedRequest) = {
  implicit val user: User = request.user
  updateUser("john@mail.com")
}