简体   繁体   中英

Dollar Sign Character in Strings

What is the cleanest method for adding a $ character in a string literal?

The best solution I've come up with so far is """${"$"}...""" , which looks ugly to me.

To escape the dollar sign inside a string literal, use the backslash character:

"\$"

To escape it in a raw string literal ( """...""" ), the workaround you provided is indeed the easiest solution at the moment. There's an issue in the bug tracker, which you can star and/or vote for: KT-2425 .

It doesn't look like you pasted your code correctly as you only have 3 double quotes.

Anyhow, the best way to do this is to just escape the dollar sign as follows:

"\$"

In current Kotlin 1.0 (and betas) you can just escape with backslash "\\$"

This passing unit test proves the cases:

@Test public fun testDollar() {
    val dollar = '$'

    val x1 = "\$100.00"
    val x2 = "${"$"}100.00"
    val x3 = """${"$"}100.00"""
    val x4 = "${dollar}100.00"
    val x5 = """${dollar}100.00"""

    assertEquals(x5, x1)
    assertEquals(x5, x2)
    assertEquals(x5, x3)
    assertEquals(x5, x4)

    // you cannot backslash escape in """ strings, therefore:

    val odd = """\$100.00""" // creates "\$100.00" instead of "$100.00"
    // assertEquals(x5, odd) would fail
}

All versions make a string "$100.00" except for the one odd case at the end.

To get literal dollar signs shows in multi-line strings, you can do the below

I'm sorry for my sins:

val nonInterpedValue = "\${someTemplate}"
val multiLineWithNoninterp = """
        Hello
        $nonInterpedValue
        World
""".trimIndent()

As mentioned elsewhere, this is the workaround because right now you can't use dollar signs inside multi-line strings. https://youtrack.jetbrains.com/issue/KT-2425

( I needed this to get Groovy's Template Engine working: https://www.baeldung.com/groovy-template-engines )

For Kotlin developers.

What I wanted to do was this:

val $name : String

If that's your case too, use this:

val `$name` : String

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM