JSON to XML in Scala and dealing with Option() result

前端 未结 4 2000
轻奢々
轻奢々 2021-01-23 01:25

Consider the following from the Scala interpreter:

scala> JSON.parseFull(\"\"\"{\"name\":\"jack\",\"greeting\":\"hello world\"}\"\"\")
res6: Option[Any] = Som         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-23 01:57

    You should probably use something like this:

    res6 collect { case x: Map[String, String] => renderXml(x) }
    

    Where:

    def renderXml(m: Map[String, String]) = 
      {m.get("name") getOrElse ""}
    

    The collect method on Option[A] takes a PartialFunction[A, B] and is a combination of filter (by a predicate) and map (by a function). That is:

    opt collect pf
    opt filter (a => pf isDefinedAt a) map (a => pf(a))
    

    Are both equivalent. When you have an optional value, you should use map, flatMap, filter, collect etc to transform the option in your program, avoiding extracting the option's contents either via a pattern-match or via the get method. You should never, ever use Option.get - it is the canonical sign that you are doing it wrong. Pattern-matching should be avoided because it represents a fork in your program and hence adds to cyclomatic complexity - the only time you might wish to do this might be for performance


    Actually you have the issue that the result of the parseJSON method is an Option[Any] (the reason is that it is an Option, presumably, is that the parsing may not succeed and Option is a more graceful way of handling null than, well, null).

    But the issue with my code above is that the case x: Map[String, String] cannot be checked at runtime due to type erasure (i.e. scala can check that the option contains a Map but not that the Map's type parameters are both String. The code will get you an unchecked warning.

提交回复
热议问题