1
我正在寫一個函數,在兩個不同的服務上調用兩個不同的方法。我調用了一個對service1執行操作的方法,並且在調用成功時(沒有拋出異常),我調用調用service2的方法。在scala中調用兩個連續的副作用方法
我的代碼如下:
def action1(param1: String, param2: String): Option[String] = {
try{
//Check if service1 contains param1
getResultsFromService1(param1) match {
//If service1 doesn't contain param1
case None => {
//Perform action to insert param1 in service 1
performActionOnService1(param1)
//Upon successful completion of the previous function
//insert param1 and param2 in service2
performActionOnService2(param1,param2)
//Assuming both the actions completed successfully return Some(param1)
//indicating, the action was successfully performed
Some(param1)
}
//Service1 contains param1
case _ => {
//Check if service2 contains params 1 and 2
getResultsFromService2(param1,param2) match {
//Service2 doesn't contain param1 and param2, insert param1 and param2
//in service1 and return Some(param1) indicating that the action was
//successfully performed
case None => performActionOnService2(param1,param2);Some(param1)
//Service 2 contains params 1 and 2, return None indicating no action was performed
case _ => None
}
}
}
}catch{
case ex:Throwable => throw ex;None
}
}
我關心我的片段與我如何撰寫這些功能的正確性沿冗長。有人能指出我在這裏做錯了什麼。
感謝
是否編譯? '例如:Throwable => throw ex; None',None無法訪問。 –
該分支返回一個值,即使在投擲的副作用下,它也會編譯 –
爲什麼要抓住所有東西來重新拋出它? –