隐式添加对象方法

KkZ*_*kZz 7 scala object implicit

有没有办法在scala对象中隐式添加方法?

更新:例如,Unfiltered scala库具有singleton对象Body,该对象包含方法Body.string(req: HttpRequest)Body.bytes(req: HttpRequest)来自http请求的读取主体.所以,我想在我的域对象中读取body,比如Body.cars(req:HttpRequest).

elb*_*ich 17

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)
    }
}
Run Code Online (Sandbox Code Playgroud)


Tom*_*icz 11

隐含地添加方法是什么意思?这段代码是否会回答您的问题:

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

"Foo".reverseUpper  //yields 'OOF'
toFunkyString("Foo").reverseUpper  //explicit invocation
Run Code Online (Sandbox Code Playgroud)