2017-09-21 33 views
0

我想編寫一個scala方法,它可以接受RuntimeException的任何子節點。我有它,但它不編譯。代碼中有什麼錯誤?編寫一個可以接受RuntimeException的子類的scala方法

def testme(e: RuntimeException): String = { 
    case e:BadRequestException=> "bad request" 
    case e: IllegalArgumentException=>"illegal argument" 
} 

我得到下面的錯誤

missing parameter type for expanded function 
[error] The argument types of an anonymous function must be fully known. (SLS 8.5) 
[error] Expected type was: String 
[error] def testme(e: RuntimeException): String = { 
[error]           ^
[error] one error found 
[error] (playWeb/compile:compileIncremental) Compilation failed 
[error] Total time: 5 s, completed Sep 21, 2017 2:45:09 PM 

回答

2

你必須指定要匹配什麼,例如添加一個e match

def testme(e: RuntimeException): String = e match { 
    case e:BadRequestException=> "bad request" 
    case e: IllegalArgumentException=>"illegal argument" 
} 
+0

感謝,但Scala的模式匹配要確切的子類實例與此匹配檢查,也可能不? – curiousengineer

+0

如果您執行'e:BadRequestException',那麼如果'e'是'BadRequestException'或其任何子類的實例,則匹配。案件按照順序進行匹配,因此首先要提供更具體的案例。 –

+0

謝謝。是的,我得到了。從本質上講,最嚴格的(或最孩子班)首先是你的意思。如果通過傳遞RuntimeException,我會感到困惑,它仍然可以匹配,我認爲它會。否則 – curiousengineer

相關問題