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
方法?
感謝。但是這使得「和」是強制性的。有沒有辦法讓它成爲可選的,而不用兩次定義方法? 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
'def hi:this.type = hi(and); def hi(a:and.type):this.type = {...}「啊,沒有定義方法兩次......不,很可能不是。 –