链接没有句点的方法调用时“不带参数”

问题描述 投票:6回答:1

我有一节课:

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

我想把new Greeter().hi.and.hello称为new 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方法?

scala
1个回答
10
投票

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

object method parameter method parameter method parameter ...

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

使用postfix语法,您可以:

((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
© www.soinside.com 2019 - 2024. All rights reserved.