scala 不带句点链接方法调用时“不带参数”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20163450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"does not take parameters" when chaining method calls without periods
提问by mparaz
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.helloas new Greeter() hi and hello
我想打电话给new Greeter().hi.and.hello为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 hias thisand tries to pass the and. But andis not an object. What can I pass to applyto chain the call to the andmethod?
我相信这意味着 Scala 会采用hiasthis并尝试通过and. 但and不是对象。我可以传递什么apply来链接对and方法的调用?
回答by Knut Arne Vedaa
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 ...
object method parameter method parameter method parameter ...
When you write new Greeter() hi and hello, andis interpreted as a parameter to the method hi.
编写时new Greeter() hi and hello,and被解释为方法的参数hi。
Using postfix syntax you coulddo:
使用后缀语法,您可以执行以下操作:
((new Greeter hi) and) hello
But that's not really recommended except for specialized DSLs where you absolutely want that syntax.
但这并不是真正推荐的,除非您绝对需要这种语法的专用 DSL。
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

