comparison content/Kotlin/multiline-strings.md @ 104:c56fdf7a343d

New blog post about Kotlin's multiline strings
author Dirk Olmes <dirk.olmes@codedo.de>
date Fri, 12 Jun 2020 12:56:06 +0200
parents
children
comparison
equal deleted inserted replaced
103:6aa2fa328a94 104:c56fdf7a343d
1 Title: Kotlin multiline strings vs the $ character
2 Date: 2020-06-12
3 Lang: en
4
5 I recently started to use [Kotlin](https://kotlinlang.org/) for small projects at work. At first I was very pleased with the language but the more I use it the more I'm stubling over things that are not nice.
6
7 I'll rumble about the braindead constructor syntax or the epic autoboxing fail with numbers some other time. Today I'll get into [multiline string templates](https://kotlinlang.org/docs/reference/basic-types.html#string-templates) and the use of the `$` character.
8
9 Kotlin, much like [Groovy](https://groovy-lang.org/) supports multiline strings. It also allows the use of `$`-epxressions in the string. Things start to become difficult if you need a literal dollar sign in the string.
10
11 Embedding literal dollar signs in Groovy multiline strings is easy:
12
13 :::java
14 name = "Dirk"
15 template = """Hello $name,
16 I owe you \$100
17 but I don't owe you the \$world"""
18 println(template)
19
20 Just escape the dollar sign with `\` and you're good to go.
21
22 Not so in Kotlin! Using a dollar sign that's escaped with backticks will fail compilation with "unresolved reference". The documentation talks about the "valid solution" for using dollar signs:
23
24 ::java
25 fun main() {
26 val name = "Dirk"
27 val template = """Hello $name,
28 I owe you $100
29 but I don't owe you the ${'$'}world"""
30 println(template)
31 }
32
33 Note how you don't have to escape the dollar sign in front of the number and the awkward escaping syntax.
34
35 [I'm not alone with this complaint](https://youtrack.jetbrains.com/issue/KT-2425) as the discussion on the ticket shows. IMHO it's not a good sign that boasts itself for "making developers happier" when little attention to this kind of details is shown. The ticket has been open for 8 years now ...
36