views:

137

answers:

3

In the example for coding with Json using Databinder Dispatch Nathan uses an Object (Http) without a method, shown here:

import dispatch._
import Http._
Http("http://www.fox.com/dollhouse/" >>> System.out )

How is he doing this?

Thank you for all of the answers unfortunatly I was not specific enough...

It looks like it is simply passing an argument to a constructor of class or companion object Http.

In another example, I've seen another form:

http = new Http
http(/* argument here */)

Is this valid Scala? I guess it must be, because the author is a Scala expert. But it makes no sense to me. Actions are usually performed by invoking methods on objects, whether explicitly as object.doSomething() or implicitly as object = something (using the apply() method underneath the syntactic sugar).

All I can think of is that a constructor is being used to do something in addition to constructing an object. In other words, it is having side effects, such as in this case going off and doing something on the web.

+6  A: 

It works by defining a method called apply on the object. If such a method is present, arguments can be applied to the object itself - which means internally the arguments are passed to the apply method.

Fabian Steeg
+3  A: 

If an object has an apply method, you can "invoke" the object as if it was a method (which will actually invoke its apply method).

sepp2k
That goes for "object" as in instance of a class *and* for "object" as in that which is defined using the Scala `object` keyword.The complement is `unapply` and `unapplySeq` which render a value suitable for use in pattern matching blocks.To round it out, `case` classes are (conceptually) shorthand for declaring a class (with compiler-supplied `equals`, `hashCode` and `toString` methods) *and* a (compiler-supplied) companion `object` with `apply`, `unapply` and possibly `unapplySeq` methods defined.
Randall Schulz
+3  A: 

I've seen another form:

val http = new Http
http(/* argument here */)

Is this valid Scala? I guess it must be, because the author is a Scala expert. But it makes no sense to me.

In the first line, the Http class's constructor is invoked to create a new instance. Nothing different than in Java. In the second line, the Http class's apply method is invoked on that instance with (/* argument here */). That's obviously a Scala-specific thing.

There can be some confusion when the class has a companion object with an apply method. In that case (assuming that apply method just invokes the companion class's construtor), new instances can be created without the new keyword:

val http = Http()

creates the new instance. This is an extremely common pattern, though companion object apply methods may do anything and have any signature.

Randall Schulz