https://kotlinlang.org logo
#getting-started
Title
# getting-started
c

Colton Idle

11/09/2023, 6:33 PM
How can I escape a $ with text that follows it. Docs seem to say using a backslash, but that doesn't work UNLESS theres a space after the dollar sign.
e

ephemient

11/09/2023, 6:38 PM
Copy code
"""some${"$"}thing"""
is the output if you ask the IDE to convert
"some\$thing"
to a raw string
c

Colton Idle

11/09/2023, 6:40 PM
interesting. i saw the docs mentioned that for multiline
i guess raw string is multiline then. thanks for the sanity check. phew
c

Casey Brooks

11/09/2023, 6:40 PM
Yup, multiline strings don’t support escape sequences (by design), so you need to use that strange
${'$'}
syntax. And it is documented at the bottom of this page
💯 2
yes, raw/multiline strings are the same thing
e

ephemient

11/09/2023, 6:42 PM
right. to be clear, raw string is maybe a slight misnomer since
$
interpolation still works but they refer to the same thing in Kotlin (some other languages use the terms differently)
and for the record,
${'$'}
and
${"$"}
both work, it doesn't matter which one you pick as the compiler will make it a static part of the string either way (it doesn't perform unnecessary constant interpolation at runtime)
c

Casey Brooks

11/09/2023, 6:45 PM
Also, to the original statement of “Docs seem to say using a backslash, but that doesn’t work UNLESS theres a space after the dollar sign.“, it’s not that the backslash works when there’s a space afterwards, it’s that you may not have noticed that the backslash ended up in the resulting string. The dollar sign is also there because the compiler saw it was not part of an interpolation https://pl.kotl.in/uKrR3RywG
j

Jeff Lockhart

11/09/2023, 8:39 PM
Roman points out:
Kotlin does not have the concept of a "raw string". Kotlin has "multiline strings".
https://youtrack.jetbrains.com/issue/KT-2425/Provide-a-way-for-escaping-the-dollar-sign-symbol-in-multiline-strings-and-string-templates
e

ephemient

11/09/2023, 8:42 PM
it's sort of true that the Kotlin docs themselves don't call it a "raw string", but the Kotlin IntelliJ plugin certainly does
j

Jeff Lockhart

11/09/2023, 9:01 PM
Yeah, I recall the docs used to mention it incorrectly somewhere too. It was fixed as a result of someone pointing it out in the comments. There's definitely a certain amount of overlap between the behavior of Kotlin multiline strings and raw strings, since you can't escape characters. It's one of the few Kotlin language features I feel falls short, where we really need true multiline and raw string support, including multiline raw strings without string interpolation.
2 Views