Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding object methods implicitly

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

like image 917
KkZz Avatar asked Oct 15 '11 21:10

KkZz


People also ask

What is an object method?

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.

How do you call a method of an object?

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.

What is implicit class in Scala?

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.


2 Answers

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)
    }
}
like image 67
elbowich Avatar answered Sep 19 '22 16:09

elbowich


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
like image 32
Tomasz Nurkiewicz Avatar answered Sep 18 '22 16:09

Tomasz Nurkiewicz