scala better syntax for map getOrElse

前端 未结 4 1948
南方客
南方客 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 11:04

    Map has its own getOrElse method, so you can just write the following:

    val t = map.getOrElse('type, "")
    

    Which accomplishes the same thing as the definition of t in your first example.


    To address your comment: If you know your map will never contain the empty string as a value, you can use the following to add the "prefix":

    map.get('type).map("prefix" + _).getOrElse("")
    

    Or, if you're using Scala 2.10:

    map.get('type).fold("")("prefix" + _)
    

    If your map can have "" values, this version will behave a little differently than yours, since it will add the prefix to those values. If you want exactly the same behavior as your version in a one-liner, you can write the following:

    map.get('type).filter(_.nonEmpty).map("prefix" + _).getOrElse("")
    

    This probably isn't necessary, though—it sounds like you don't expect to have empty strings in your map.

提交回复
热议问题