Skip to content
Home » Dollar sign in Kotlin

Dollar sign in Kotlin

  • by
Dollar sign in Kotlin

1. Overview

In this article, we will learn the dollar sign in Kotlin (String templates) and also escape the dollar sign in a raw and single-line text.

You can look into our Kotlin articles to know more about other topics.

Kotlin has two types of the string literal:

  • escaped strings that may contain escaped characters (For example: val s = "Hello, world!\n"). You can escape the characters in a conventional way, with a backslash (\).
  • raw strings that can contain newlines and arbitrary text and do not support backslash escaping.

2. Kotlin string templates using dollar sign

The String templates allow you to include variable references and expressions into strings. In other words, it refers to pieces of code that are evaluated and whose results are concatenated into the string.

When there is any request for the value of the string, it substitutes all references and expressions with actual values.

For example, the following string i contains a reference to the value of another variable j.

val j = 10
val i = "This is a string template $j"
println(i)

Here, the String literals contain template expressions.

A template expression starts with a dollar sign ($) and comprises a variable name:

val i = 1000
println("i = $i") // prints "i = 1000"

String template can also be an expression in curly braces:

val s = "abc"
println("$s.length is ${s.length}") // prints "abc.length is 3"

You can use templates both in raw and escaped strings.

3. Escape dollar sign in a string

You can escape the $ character in single-line text or raw text.

1. The raw text doesn’t support backslash escaping. As discussed earlier, Kotlin interprets the $ as an identifier to insert values of variables or expressions in a String.

If you want to insert the $ as a character in a raw string, use the following syntax:

val price = """
${'$'}20
"""

println(price) // prints "$20"

2. In a escaped or single line text, you can use backslash escaping:

val singleLineText = "\$"
println(singleLineText)
// prints "$"

4. Conclusion

To sum up, we have learned the dollar sign in Kotlin. You can look into our Kotlin articles to know more about other topics.

You can check out our GitHub repository for code samples.

Leave a Reply

Your email address will not be published. Required fields are marked *