Teimuraz
Teimuraz

Reputation: 9325

Scala: How to pass property of implicit instance of class implicitly?

I have following code:

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("[email protected]") // <-- 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
  }

}

From above, is it possible to pass request.user in updateUserAction method to the updateUser method implicitly?

Upvotes: 1

Views: 274

Answers (2)

Michael Zajac
Michael Zajac

Reputation: 55569

Make an implicit conversion from WrappedRequest to User so that all of your methods that require a WrappedRequest will have access to an implicit User.

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

Upvotes: 6

Tzach Zohar
Tzach Zohar

Reputation: 37822

Like this?

def updateUserAction(implicit request: WrappedRequest) = {
  implicit val user: User = request.user
  updateUser("[email protected]")
}

Upvotes: 2

Related Questions