How to do escaping idiomatically in Scala -


Suppose I am writing a simple task to avoid XML strings.

  val map = map ('&'; '' - & gt; "& amp; amp;", '& lt;' - & gt; "& amp; lt;" '& Gt;' - & gt; "& amp; g;") // ... more def escape (str: string): string = {val w = new java.io.StringWriter () & Lt; - str) if (map.contains (c)) w.write (map (c)) other w .write (c); It does not look like  idiomatically  in Scala and besides, I do not know how to deal with  map , which mapped the characters to avoid strings. How do you fix this? 

real life solution

just use:

  scala & gt; Scala.xml.Utility.escape (foo) res7: string = & amp; Amp; Amp; Amp; Amp; the lift; Bar & amp; Hello  

If you are still interested in doing this:

First of all, & amp; and ; There is no need to repeat the parts in the map of the escape:

  Scala> Val Escape = Map ('& amp; amp; & amp;; amp;' 'amp'; '& lt;' - & gt; "lt", & gt; - - & gt; "gt")  Pre> 

It is simple and fast because they are in Theo ... but since you have asked to learn this question ...)

  scala> Def escapeChar (c: char) = Escapes.get (c) .map {x = & gt; S "& amp; $ x,"} escape: (c: four) option [string] scale & gt; Def escapeStr (s: string) = s.flatMap {c = & gt; EscapeChar (c) .getOrElse (c.toString)} escapeStr: (S: string) string scale & gt; EscapeStr ("& amp; foo & lt; times> halo") res9: string = & amp; Amp; Amp; Amp; Lt; Bar & gt; Hello  

... You can only escape (C: variable) function, but I think it is more readable in this way.

If you are interested: this works by treating the string as a sequence of characters; You can use flatmap on it, which allows you to map to each character from more than one character (a string ); flatMap then combines all the emitted strings into a single string. The characters that do not need to be saved are mapped for one-four stars.


Comments