scala better syntax for map getOrElse

前端 未结 4 1871
南方客
南方客 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:14

    You could also use the Scalaz Zero typeclass so your code would look like below. The unary operator is defined on OptionW.

    val t = ~map.get('type)                 // no prefix
    val t = ~map.get('type).map("prefix"+_) // prefix
    

    Here's an example session:

    scala> import scalaz._; import Scalaz._
    import scalaz._
    import Scalaz._
    
    scala> val map = Map('type -> "foo")
    map: scala.collection.immutable.Map[Symbol,java.lang.String] = Map('type -> foo)
    
    scala> ~map.get('type)
    res3: java.lang.String = foo
    
    scala> ~map.get('notype)
    res4: java.lang.String = ""
    
    scala> ~map.get('type).map("prefix"+_)
    res5: java.lang.String = prefixfoo
    
    scala> ~map.get('notype).map("prefix"+_)
    res6: java.lang.String = ""
    

提交回复
热议问题