2017-02-04 47 views
0

空我有一個函數斯卡拉 - 不使用的情況下聲明後衛

def withEnrichment[T](f: (AccountEnrichment) => Option[T] Or ErrorMessage) = 
     (Option(xa.getEnrichment) match { 
    case None => Good(None) 
    case Some(e: AccountEnrichment) => f(e) 
    case _ => Bad("not an AccountEnrichment")}) 
badMap {"enrichment: " + _} 

我需要保護添加到它,因此它會忽略特定類型的賬戶。

case Some(g: AccountEnrichment) 
    if (g.getAccount != null && g.getAccount.getId == "BADACCOUNT") 
     => Bad("account: id cannot be BADACCOUNT") 

這是有效的,但是我希望不使用null關鍵字。 g.getAccount來自Java庫,可以並且將爲null。

+0

你爲什麼要避免空檢查比較的任何原因? –

回答

1

當一個選項應用於null時,它返回None。

scala> Option(null) 
res0: Option[Null] = None 

Option的這個屬性可以用來代替你的代碼中的空比較。

case Some(g: AccountEnrichment) 
    if (Option(g.getAccount).isEmpty && g.getAccount.getId == "BADACCOUNT") 
     => Bad("account: id cannot be BADACCOUNT") 
+0

謝謝,與.isNotEmpty合作 – Saf

1

我覺得你並不需要一個額外的case與保護,如果你已經有了case Some(e: AccountEnrichment) => f(e)。您可以將其修改爲:

case Some(e: AccountEnrichment) => Option(e.getAccount) 
    .filterNot(_.getId == "BADACCOUNT") 
    .map(_ => f(e)) 
    .getOrElse(Bad("account: id cannot be BADACCOUNT"))