为了账号安全,请及时绑定邮箱和手机立即绑定

了解Scala中的隐式

了解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什么时候应该使用,为什么?
查看完整描述

3 回答

?
郎朗坤

TA贡献1921条经验 获得超9个赞

明智地包含讽刺!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")

}


查看完整回答
反对 回复 2019-11-04
  • 3 回答
  • 0 关注
  • 438 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信