scala better syntax for map getOrElse

前端 未结 4 1967
南方客
南方客 2021-02-05 10:29

is there a better way to write the code below?

val t = map.get(\'type).getOrElse(\"\"); 
if (t != \"\") \"prefix\" + t;

be interested in inline

4条回答
  •  遇见更好的自我
    2021-02-05 10:56

    While reading the book Play for Scala, I picked up this code snippet that was defined in a controller, which might be a better syntax for getOrElse.

    def show(ean: Long) = Action { implicit request =>
    
      Product.findByEan(ean).map { product =>
        Ok(views.html.products.details(product))
      }.getOrElse(NotFound)
    
    }
    

    In which, the Product.findByEan(ean: Long) was defined like

    def findByEan(ean: Long) = products.find(_ean == ean)
    

提交回复
热议问题