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)
.
An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method. In addition to objects that are predefined in the browser, you can define your own objects.
To call an object's method, simply append the method name to an object reference with an intervening '. ' (period), and provide any arguments to the method within enclosing parentheses. If the method does not require any arguments, just use empty parentheses.
Scala 2.10 introduced a new feature called implicit classes. An implicit class is a class marked with the implicit keyword. This keyword makes the class's primary constructor available for implicit conversions when the class is in scope. Implicit classes were proposed in SIP-13.
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)
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With