I recently started to use Kotlin 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 and the use of the $ character.

Kotlin, much like Groovy 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:

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:

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 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 …