Adding object methods implicitly

我的未来我决定 提交于 2020-01-11 02:17:38

问题


Is there a way to implicitly add methods in scala object?

Upd: For example, Unfiltered scala library have singleton object Body which contains methods Body.string(req: HttpRequest) and Body.bytes(req: HttpRequest) for read body from http request. So, I want read body in my domain objects, like Body.cars(req:HttpRequest).


回答1:


import scala.language.implicitConversions

object ObjA

object ObjB {
  def x = 1
}

object Main {
    implicit def fromObjA(objA: ObjA.type) = ObjB

    def main(args: Array[String]): Unit = {
        println(ObjA.x)
    }
}



回答2:


What do you mean by implicitly adding methods? Does this code snipper answer your question:

implicit def toFunkyString(s: String) = new {
  def reverseUpper = s.reverse.toUpperCase
}

"Foo".reverseUpper  //yields 'OOF'
toFunkyString("Foo").reverseUpper  //explicit invocation


来源:https://stackoverflow.com/questions/7780937/adding-object-methods-implicitly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!