Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"does not take parameters" when chaining method calls without periods

Tags:

scala

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?

like image 512
mparaz Avatar asked Nov 23 '13 14:11

mparaz


1 Answers

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
like image 102
Knut Arne Vedaa Avatar answered Sep 28 '22 07:09

Knut Arne Vedaa