Mercurial > hg > Blog
view content/Kotlin/multiline-strings.md @ 110:be0331916375
README
author | Dirk Olmes <dirk.olmes@codedo.de> |
---|---|
date | Fri, 18 Jun 2021 07:24:40 +0200 |
parents | c56fdf7a343d |
children |
line wrap: on
line source
Title: Kotlin multiline strings vs the $ character Date: 2020-06-12 Lang: en 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. 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. 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. Embedding literal dollar signs in Groovy multiline strings is easy: :::java name = "Dirk" template = """Hello $name, I owe you \$100 but I don't owe you the \$world""" println(template) Just escape the dollar sign with `\` and you're good to go. 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: ::java fun main() { val name = "Dirk" val template = """Hello $name, I owe you $100 but I don't owe you the ${'$'}world""" println(template) } Note how you don't have to escape the dollar sign in front of the number and the awkward escaping syntax. [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 ...