I have a class:
class Greeter {
def hi = { print ("hi"); this }
def hello = { print ("hello"); this }
def and = this
}
I would like to call the new Greeter().hi.and.hello
as new Greeter() hi and hello
but this results in:
error: Greeter does not take parameters
g hi and hello
^
(note: the caret is under "hi")
I believe this means that Scala is takes the hi
as this
and tries to pass the and
. But and
is not an object. What can I pass to apply
to chain the call to the and
method?
You can't chain parameterless method calls like that. The general syntax that works without dots and parentheses is (informally):
object method parameter method parameter method parameter ...
When you write new Greeter() hi and hello
, and
is interpreted as a parameter to the method hi
.
Using postfix syntax you could do:
((new Greeter hi) and) hello
But that's not really recommended except for specialized DSLs where you absolutely want that syntax.
Here's something you could play around with to get sort of what you want:
object and
class Greeter {
def hi(a: and.type) = { print("hi"); this }
def hello = { print("hello"); this }
}
new Greeter hi and hello
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