了解Scala中的隐式

我正在通过Scala Playframework教程学习时,遇到了让我感到困惑的这段代码:


def newTask = Action { implicit request =>

taskForm.bindFromRequest.fold(

        errors => BadRequest(views.html.index(Task.all(), errors)),

        label => {

          Task.create(label)

          Redirect(routes.Application.tasks())

        } 

  )

}

因此,我决定进行调查并发现这篇文章。


我还是不明白。


这有什么区别:


implicit def double2Int(d : Double) : Int = d.toInt


def double2IntNonImplicit(d : Double) : Int = d.toInt

除了显而易见的事实,它们具有不同的方法名称。


我implicit什么时候应该使用,为什么?


一只甜甜圈
浏览 443回答 3
3回答

郎朗坤

明智地包含讽刺!YMMV ...路易吉的答案是完整而正确的。这只是通过举例说明如何光荣地过度使用隐式实例来扩展它,因为它在Scala项目中经常发生。实际上,您经常甚至可以在“最佳实践”指南之一中找到它。object HelloWorld {  case class Text(content: String)  case class Prefix(text: String)  implicit def String2Text(content: String)(implicit prefix: Prefix) = {    Text(prefix.text + " " + content)  }  def printText(text: Text): Unit = {    println(text.content)  }  def main(args: Array[String]): Unit = {    printText("World!")  }  // Best to hide this line somewhere below a pile of completely unrelated code.  // Better yet, import its package from another distant place.  implicit val prefixLOL = Prefix("Hello")}
打开App,查看更多内容
随时随地看视频慕课网APP