Sebastian
Sebastian

Reputation: 45

Scala function call

I have found following function calls in several frameworks which appear to me as if the framework extends some base classes. Some examples:

within(500 millis)

or

"Testcase description" in
  { .... }

First example returns a duration object with the duration of 500 milliseconds from akka and second is the definition of a testcase from scalatest.

I would like to know how this behavior is achieved and how it is called.

Upvotes: 3

Views: 420

Answers (2)

IttayD
IttayD

Reputation: 29113

This is done with the "Pimp my library" technique.

To add non existing methods to a class, you define an implicit method that converts objects of that class to objects of a class that has the method:

class Units(i: Int) {
  def millis = i
}

implicit def toUnits(i: Int) = new Units(i)


class Specs(s: String) {
  def in(thunk: => Unit) = thunk
}

implicit def toSpecs(s: String) = new Specs(s)

See also "Where does Scala looks for Implicits?"

Upvotes: 10

hammar
hammar

Reputation: 139830

If I'm not mistaken, those pieces of code can be desugared as

within(500.millis)

and

"Testcase description".in({ ... })

This should make it easier to see what's going on.

Upvotes: 1

Related Questions