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

1
  • Please explain better what you want. Commented Oct 16, 2011 at 0:51

2 Answers 2

19
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)
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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...
@EduardoBezerra I updated the answer to work with 2.11.7, but I don't use Scala nowadays, so any suggestions are welcome.
11

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

1 Comment

"Foo" is a class instance, what I mean is adding methods in singleton object, something like Math.myMethod(1). Is it all the same?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.