“不带参数"当没有句点链接方法调用时 [英] "does not take parameters" when chaining method calls without periods

查看:44
本文介绍了“不带参数"当没有句点链接方法调用时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂课:

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.但是 不是一个对象.我可以传递给 apply 什么来将调用链接到 and 方法?

I believe this means that Scala is takes the hi as this and tries to pass the and. But and is not an object. What can I pass to apply to chain the call to the and method?

推荐答案

你不能像那样链接无参数方法调用.不带点和括号的通用语法是(非正式地):

You can't chain parameterless method calls like that. The general syntax that works without dots and parentheses is (informally):

对象方法参数方法参数方法参数...

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

When you write new Greeter() hi and hello, and is interpreted as a parameter to the method hi.

使用后缀语法你可以做到:

((new Greeter hi) and) hello

但这并不是真正推荐的,除非您绝对需要这种语法的专用 DSL.

But that's not really recommended except for specialized DSLs where you absolutely want that syntax.

这里有一些你可以玩的东西来获得你想要的东西:

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

这篇关于“不带参数"当没有句点链接方法调用时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆