我有一堂课:
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
的参数。
使用后缀语法,您可以执行以下操作:
((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