我有以下代码:
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 方法吗?
答案 0 :(得分:5)
进行从WrappedRequest
到User
的隐式转换,以便所有需要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")
}