Skip to content

Instantly share code, notes, and snippets.

@danclien
Last active December 21, 2015 06:18
Show Gist options
  • Save danclien/6262777 to your computer and use it in GitHub Desktop.
Save danclien/6262777 to your computer and use it in GitHub Desktop.

Had a WTF moment figuring out how Actions in Play Framework could be defined with and without an implicit request.

package controllers

import play.api.mvc._

object ApplicationController extends Controller {
  def index = Action {
    Ok("Without implicit request")
  }

  def indexWithImplicit = Action { implicit request => //WTF is this magic?
    Ok("With implicit request")
  }
}

Figured out it was calling two seperate apply methods. Simplified example:

object Foo {
  def apply(f: Int => String) : String = {  //accept a function as a parameter
    println("apply with function")
    val num = 42
    f(num)
  }
  
  def apply(input: String) : String = {     //accepts a string as a parameter
    println("apply with String")
    println(s"input: $input")
    input
  }
}

def withImplicit = Foo { implicit num =>    //anonymous function returning a string
  println(s"With implicit num = $num")      //`implicit num` is the same as
  num.toString                              //`num => implicit val numImp = num;`
}

def withoutImplicit = Foo {                 //block of type string
  println("Without implicit num")
  "0"
}

withImplicit      //42
withoutImplicit   //0
@bretthoerner
Copy link

Yeah, total pros and cons of DSLs in action here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment