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
Yeah, total pros and cons of DSLs in action here.