2013-11-23 22 views
5

我有一個類:斯卡拉「不帶參數」當鏈接方法調用,而不時期

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
^
(注意:插入符號在「hi」下)

我相信這意味着Scala需要hi作爲this並嘗試通過and。但and不是一個對象。我可以傳遞給apply以將呼叫鏈接到and方法?

回答

8

不能像這樣鏈接無參數的方法調用。如果沒有點工作和括號的一般語法(非正式):

object method parameter method parameter method parameter ...

當你寫new Greeter() hi and helloand被解釋爲參數的方法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 
+0

感謝。但是這使得「和」是強制性的。有沒有辦法讓它成爲可選的,而不用兩次定義方法? This works: 'def hi(a:and.type)= {print(「hi」);這個}' 'def hi = {print(「hi」);這個}' 但是,如果我做到了這一點: 'def hi(a:and.type = and)= {print(「hi」);這個}' 然後: '新希望你好和'是允許的,但只是'新希望嗨'不是 - 現在需要括號,像'new Greeter hi()'。 – mparaz

+1

'def hi:this.type = hi(and); def hi(a:and.type):this.type = {...}「啊,沒有定義方法兩次......不,很可能不是。 –