繁体   English   中英

在Scala中编写此功能的更实用,更简洁的方法

[英]More functional and concise way to write this in Scala

我从(使用“播放操作”方法)开始:

    val foo = JPA.em.find(classOf[Foo], id)
    if (foo == null) NotFound("Bad Id") else Ok(Json.toJson(foo))

不喜欢它的必要性,我去了:

    Option(JPA.em.find(classOf[Foo], id)) match {
      case Some(foo) => Ok(Json.toJson(foo))
      case None => NotFound("Bad Id")
    }

功能更多,但更长。

对于该问题的一般性质,我深表歉意,但我敢肯定,答案可能对许多人有帮助。

Option(JPA.em.find(classOf[Foo], id)).map(foo=>Ok(Json.toJson(foo))).getOrElse(NotFound("Bad Id"))

绝对值得将不安全的Java API与这样的可重用方法一起包装,这些方法返回Option ,例如

def findOpt[T](cls: Class[T], id: Object): Option[T] =
  Option(JPA.em.find(cls, id))

使用此API而不是直接使用JPA,意味着您无需担心代码中其他地方的空检查。 全部都集中在一个地方。

现在,您可以决定是否使用matchfoldmap / getOrElse ; 重要的是,结果的可能缺失以findOpt的类型findOpt

findOpt(classOf[Foo], id) map (foo => OK(Json.toJson(foo)) getOrElse NotFound("Bad Id")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM