You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The `f` interpolator makes use of the string format utilities available from Java. The formats allowed after the `%` character are outlined in the
80
102
[Formatter javadoc](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Formatter.html#detail). If there is no `%` character after a variable
@@ -105,42 +127,100 @@ In Scala, all processed string literals are simple code transformations. Anyti
105
127
id"string content"
106
128
107
129
it transforms it into a method call (`id`) on an instance of [StringContext](https://www.scala-lang.org/api/current/scala/StringContext.html).
108
-
This method can also be available on implicit scope. To define our own string interpolation, we simply need to create an implicit class that adds a new method
109
-
to `StringContext`. Here's an example:
130
+
This method can also be available on implicit scope.
131
+
To define our own string interpolation, we need to create an implicit class (Scala 2) or an `extension` method (Scala 3) that adds a new method to `StringContext`.
132
+
Here's an example:
110
133
111
-
// Note: We extends AnyVal to prevent runtime instantiation. See
112
-
// value class guide for more info.
113
-
implicit class JsonHelper(val sc: StringContext) extends AnyVal {
In this example, we're attempting to create a JSON literal syntax using string interpolation. The `JsonHelper` implicit class must be in scope to use this syntax, and the json method would need a complete implementation. However, the result of such a formatted string literal would not be a string, but a `JSONObject`.
122
164
123
165
When the compiler encounters the literal `json"{ name: $name, id: $id }"` it rewrites it to the following expression:
124
166
125
-
new StringContext("{ name: ", ", id: ", " }").json(name, id)
So, the `json` method has access to the raw pieces of strings and each expression as a value. A simplified (buggy) implementation of this method could be:
Each of the string portions of the processed string are exposed in the `StringContext`'s `parts` member. Each of the expression values is passed into the `json` method's `args` parameter. The `json` method takes this and generates a big string which it then parses into JSON. A more sophisticated implementation could avoid having to generate this string and simply construct the JSON directly from the raw strings and expression values.
0 commit comments