Scala通过将函数作为参数传递隐式参数来感受adnvatage

ses*_*ses 4 scala

我试着感受implicitScala 中参数的优势.(已编辑:使用匿名函数时的特殊情况.请查看此问题中的链接)

我尝试根据这篇文章进行简单的模拟.在哪里解释如何Action工作PlayFramework.这也涉及到.

以下代码用于此目的:

object ImplicitArguments extends App {

  implicit val intValue = 1 // this is exiting value to be passed implicitly to everyone who might use it

  def fun(block: Int=>String): String = { // we do not use _implicit_ here !
    block(2)  // ?? how to avoid passing '2' but make use of that would be passed implicitly ?
  }

  // here we use _implicit_ keyword to make it know that the value should be passed !
  val result = fun{ implicit intValue =>  {  // this is my 'block'
                         intValue.toString     // (which is anonymous function)
                       }
  }

 println(result) // prints 2

}
Run Code Online (Sandbox Code Playgroud)

我想打印"1".

如何避免传递魔法"2"但使用隐含定义的"1"?

另请参阅我们在定义中不使用的情况implicit,但它存在,因为匿名函数传递implicit.

编辑: 以防万一,我发布了另一个例子 - 简单模拟Play'如何Action工作:

  object ImplicitArguments extends App {

  case class Request(msg:String)

  implicit val request = Request("my request")

  case class Result(msg:String)

  case class Action(result:Result)
  object Action {
    def apply(block:Request => Result):Action = {
     val result = block(...) // what should be here ??
     new Action(result)
    }
  }

  val action = Action { implicit request =>
    Result("Got request [" + request + "]")
  }

  println(action)

}
Run Code Online (Sandbox Code Playgroud)

edo*_*fic 6

Implicits不能像这样工作.没有魔力.它们只是(通常)隐藏的参数,因此在调用函数时会被解析.

有两种方法可以使您的代码工作.

你可以修复所有调用的隐含值 fun

def fun(block: Int=>String): String = { 
  block(implicitly[Int]) 
}
Run Code Online (Sandbox Code Playgroud)

implicitly是Predef中定义的函数.再一次没有魔力.这是它的定义

def implicitly[A](implicit value: A) = value
Run Code Online (Sandbox Code Playgroud)

但是,这意味着什么时候会解决的隐含价值声明fun,而不是每次调用.

如果要为不同的调用使用不同的值,则需要添加隐式参数

def fun(block: Int=>String)(implicit value: Int): String = { 
  block(value) 
}
Run Code Online (Sandbox Code Playgroud)

现在,这将取决于呼叫站点的隐式范围.你可以像这样轻松覆盖它

val result = fun{ _.toString }(3)
Run Code Online (Sandbox Code Playgroud)

结果将是"3"因为3最后的明确.但是,没有办法神奇地fun将声明从声明更改为从隐式作用域中获取值.

我希望你现在能够更好地理解隐含的内容,起初它们可能有点棘手.