我有一节课:
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
方法?
你不能像这样链接无参数方法调用。没有圆点和圆括号的一般语法是(非正式地):
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