8

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).

KkZz
  • 83
  • 1
  • 5

2 Answers2

18
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)
    }
}
elbowich
  • 1,941
  • 1
  • 13
  • 12
  • 1
    I didn't get it... Is this the whole source file? Like ObjB.scala? Or is this part of some method implementation? I tried putting just this in my code and it didn't work... – Eduardo Bezerra Feb 11 '16 at 11:46
  • @EduardoBezerra I updated the answer to work with 2.11.7, but I don't use Scala nowadays, so any suggestions are welcome. – elbowich Feb 11 '16 at 18:37
12

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
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • 1
    `"Foo"` is a class instance, what I mean is adding methods in singleton object, something like `Math.myMethod(1)`. Is it all the same? – KkZz Oct 16 '11 at 11:42