Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Yes, there is a way to eliminate <code>_user</code> variable while making <code>user</code> implicit:</p> <pre><code>def index(id:String) = Action { User.findById(id) map (implicit user =&gt; hello("implicit")) getOrElse BadRequest } </code></pre> <p><strong>UPDATE:</strong> Addressing your question about many cases in the comments below.</p> <p>It all depends what value type is returned by <code>User.findById</code>. If it's <code>Option[User]</code> but you want to match on specific users (assuming <code>User</code> is a case class), then the original solution still applies:</p> <pre><code>def index(id:String) = Action { User.findById(id) map { implicit user =&gt; user match { case User("bob") =&gt; hello("Bob") case User("alice") =&gt; hello("Alice") case User("john") =&gt; hello("John") case _ =&gt; hello("Other user") } } getOrElse BadRequest </code></pre> <p>Or you can match on anything else if you want, as long as <code>User.findById</code> is <code>String =&gt; Option[User]</code></p> <p>If, on the other hand, <code>User.findById</code> is <code>String =&gt; User</code> then you can simply define a helper object like:</p> <pre><code>object withUser { def apply[A](user: User)(block: User =&gt; A) = block(user) } </code></pre> <p>And use it as follows (again assuming <code>User</code> is a case class):</p> <pre><code>def index(id: String) = Action { withUser(User findById id) { implicit user =&gt; user match { case User("bob") =&gt; hello("Bob") case User("alice") =&gt; hello("Alice") case User("john") =&gt; hello("John") case _ =&gt; BadRequest } } } </code></pre> <p>or matching on some other value, say an <code>Int</code>:</p> <pre><code>def index(id: String, level: Int) = Action { withUser(User findById id) { implicit user =&gt; level match { case 1 =&gt; hello("Number One") case 2 =&gt; hello("Number Two") case 3 =&gt; hello("Number Three") case _ =&gt; BadRequest } } } </code></pre> <p>I hope this covers all the scenarios you may have.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload