2011-05-02 84 views
3

我正在使用Scala match/case語句來匹配給定java類的接口。我希望能夠檢查一個類是否實現了接口的組合。我似乎得到這個工作的唯一方法是使用嵌套的match/case陳述,這看起來很醜。匹配Java接口時的Scala匹配/ case語句

可以說我有一個PersonImpl對象,它實現了Person,Manager和Investor。我想看看PersonImpl是否實現了經理和投資者。我應該可以做到以下幾點:

person match { 
    case person: (Manager, Investor) => 
    // do something, the person is both a manager and an investor 
    case person: Manager => 
    // do something, the person is only a manager 
    case person: Investor => 
    // do something, the person is only an investor 
    case _ => 
    // person is neither, error out. 
} 

case person: (Manager, Investor)只是不起作用。爲了得到它的工作,我必須做到以下看起來很醜陋。

person match { 
    case person: Manager = { 
    person match { 
     case person: Investor => 
     // do something, the person is both a manager and investor 
     case _ => 
     // do something, the person is only a manager 
    } 
    case person: Investor => 
    // do something, the person is only an investor. 
    case _ => 
    // person is neither, error out. 
} 

這簡直太難看了。有什麼建議麼?

+0

'情況的人:經理Investor'應該工作。當你對這些對象調用一個'Investor'方法時會發生什麼,你說的只是'Manager'? – 2011-05-02 20:14:22

+0

如果您可以接受答案或告訴我們您想知道關於此主題的其他信息,那將是非常好的。 – 2011-05-24 09:42:55

回答

8

試試這個:

case person: Manager with Investor => // ... 

with用於其它情況下,您可能想表達型路口,例如在類型限制:

def processGenericManagerInvestor[T <: Manager with Investor](person: T): T = // ... 

順便說一句 - 不,這是建議的做法,但是 - 你隨時可以測試它像這樣還有:if (person.isInstanceOf[Manager] && person.isInstanceOf[Investor]) ...


編輯:這很適合我:

trait A 
trait B 
class C 

def printInfo(a: Any) = println(a match { 
    case _: A with B => "A with B" 
    case _: A => "A" 
    case _: B => "B" 
    case _ => "unknown" 
}) 

def main(args: Array[String]) { 
    printInfo(new C)    // prints unknown 
    printInfo(new C with A)  // prints A 
    printInfo(new C with B)  // prints B 
    printInfo(new C with A with B) // prints A with B 
    printInfo(new C with B with A) // prints A with B 
} 
+0

我剛剛測試過案例:經理與投資者,不幸的是它沒有工作。它捕獲只實施經理的人員以及實施兩者的人員。這是一個錯誤? – user523078 2011-05-02 16:27:57

+0

好笑。我在我的答案中添加了一個簡短的例子,對我來說Scala 2.8.1很適合。你正在使用哪個版本? – 2011-05-02 16:33:38

+0

你是對的。我只是運行你的例子,它的工作。在我的情況下,我沒有使用traits,因爲「class」是一個java並正在實現一個接口,但我認爲這不重要。 – user523078 2011-05-02 18:30:06