@@ -20,42 +20,36 @@ object Show extends LowPrioShow {
20
20
ev.show(v)
21
21
}
22
22
23
- implicit val stringShow : Show [String ] = new Show [String ] {
23
+ /** Adds escaping backslashes in a string so that it could be put in source code.
24
+ * For example, a newline character is shown as '\n' (without the quotes).
25
+ * Chars that don't have to be escaped are simply converted to a string.
26
+ * @param c the char to be escaped
27
+ * @return a string describing how to escape the give char in source code.
28
+ */
29
+ private def escapeChar (c : Char ): String = c match {
24
30
// From 2.12 spec, `charEscapeSeq`:
25
31
// ‘\‘ (‘b‘ | ‘t‘ | ‘n‘ | ‘f‘ | ‘r‘ | ‘"‘ | ‘'‘ | ‘\‘)
26
- def show (str : String ) = {
27
- val sb = new StringBuilder
28
- sb.append(" \" " )
29
- str.foreach {
30
- case '\b ' => sb.append(" \\ b" )
31
- case '\t ' => sb.append(" \\ t" )
32
- case '\n ' => sb.append(" \\ n" )
33
- case '\f ' => sb.append(" \\ f" )
34
- case '\r ' => sb.append(" \\ r" )
35
- case '\' ' => sb.append(" \\ '" )
36
- case '\" ' => sb.append(" \\\" " )
37
- case c => sb.append(c)
38
- }
39
- sb.append(" \" " )
40
- sb.toString
41
- }
32
+ case '\b ' => " \\ b"
33
+ case '\t ' => " \\ t"
34
+ case '\n ' => " \\ n"
35
+ case '\f ' => " \\ f"
36
+ case '\r ' => " \\ r"
37
+ case '\' ' => " \\ '"
38
+ case '\" ' => " \\\" "
39
+ case '\\ ' => " \\\\ "
40
+ case c => c.toString
41
+ }
42
+
43
+ implicit val stringShow : Show [String ] = new Show [String ] {
44
+ def show (str : String ) = str.flatMap(escapeChar).mkString(" \" " , " " , " \" " )
42
45
}
43
46
44
47
implicit val floatShow : Show [Float ] = new Show [Float ] {
45
48
def show (f : Float ) = f + " f"
46
49
}
47
50
48
51
implicit val charShow : Show [Char ] = new Show [Char ] {
49
- def show (c : Char ) = " '" + (c match {
50
- case '\b ' => " \\ b"
51
- case '\t ' => " \\ t"
52
- case '\n ' => " \\ n"
53
- case '\f ' => " \\ f"
54
- case '\r ' => " \\ r"
55
- case '\' ' => " \\ '"
56
- case '\" ' => " \\\" "
57
- case c => c
58
- }) + " '"
52
+ def show (c : Char ) = s " ' ${escapeChar(c)}' "
59
53
}
60
54
61
55
implicit def showList [T ](implicit st : Show [T ]): Show [List [T ]] = new Show [List [T ]] {
0 commit comments