我有一堂课:

class Greeter {
    def hi = { print ("hi"); this }
    def hello = { print ("hello"); this }
    def and = this
}


我想称new Greeter().hi.and.hellonew Greeter() hi and hello

但这导致:

error: Greeter does not take parameters
              g hi and hello
                ^
(note: the caret is under "hi")


我相信这意味着Scala将hi作为this并尝试通过and。但是and不是对象。我可以传递给apply以将调用链接到and方法的什么?

最佳答案

您不能像这样链接无参数方法调用。没有点和括号的常规语法是(非正式地):

object method parameter method parameter method parameter ...

编写new Greeter() hi and hello时,and被解释为方法hi的参数。

使用后缀语法,您可以执行以下操作:

((new Greeter hi) and) hello


但这不是真正推荐的方法,除非您确实需要该语法的专用DSL除外。

您可以尝试以下操作来获得所需的内容:

object and

class Greeter {
  def hi(a: and.type) = { print("hi"); this }
  def hello = { print("hello"); this }
}

new Greeter hi and hello

07-24 09:45
查看更多