Search code examples
kotlinstringtemplate

Kotlin: Is it possible to change the way string templates are evaluated?


This is purely a theoretical question, but I'm wondering, whether it's possible to change the way objects are serialized in string templates like in "value: $value"?

With the research I've done so far, this seems to not be possible, but the syntax I had in mind would be something like Context.run { "value: $value" }, where the context may decide how value is serialized (e.g. special treatment for certain classes, escape strings).

Applications would for example be uri builders or any other context which requires encoding. No more "https://www.example.com/?${key.toString().urlEscape()}=${value.toString().urlEscape()}", just UrlBuilder.run{ "https://www.example.com/?$key=$value" } where urlEscape is applied to all arguments by the url builder.

I'm really just curious about syntax improvements, I don't have an active issue without workaround.


Solution

  • This is not possible. From the Kotlin Language Specification.

    An interpolated value v is converted to kotlin.String according to the following convention:

    If it is equal to the null reference, the result is "null"; Otherwise, the result is v.toString() where toString is the kotlin.Any member function (no overloading resolution is performed to choose this function in this context).

    So you cannot control this in any other way than to override toString in the class of the interpolated value.