链接没有句点的方法调用时,Scala"不接受参数"

mpa*_*raz 6 scala

我有一节课:

class Greeter {
    def hi = { print ("hi"); this }
    def hello = { print ("hello"); this }
    def and = this
}
Run Code Online (Sandbox Code Playgroud)

我想打电话给new Greeter().hi.and.hellonew Greeter() hi and hello

但结果是:

hi (注意:插入符号在"hi"下)

我相信这意味着Scala会采用thisas and并尝试通过and.但apply不是一个对象.我可以传递什么and来链接调用new Greeter().hi.and.hello方法?

Knu*_*daa 10

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

object method parameter method parameter method parameter ...

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

使用postfix语法,您可以:

((new Greeter hi) and) hello
Run Code Online (Sandbox Code Playgroud)

但是除了你绝对需要这种语法的专业DSL之外,这并不是真正推荐的.

这是你可以玩的东西,以获得你想要的东西:

object and

class Greeter {
  def hi(a: and.type) = { print("hi"); this }
  def hello = { print("hello"); this }
}

new Greeter hi and hello
Run Code Online (Sandbox Code Playgroud)