2017-02-04 46 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"))