gpt4 book ai didi

scala - "does not take parameters"链接方法调用时没有句点

转载 作者:行者123 更新时间:2023-12-04 14:01:17 26 4
gpt4 key购买 nike

我有一个类:

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 采用 hithis并试图通过 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

关于scala - "does not take parameters"链接方法调用时没有句点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20163450/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com