亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

了解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 關注
  • 492 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號