0
0
KotlinConceptBeginner · 3 min read

What is Raw String in Kotlin: Simple Explanation and Example

In Kotlin, a raw string is a string literal enclosed in triple quotes """ that can contain newlines and special characters without needing escape sequences. It lets you write text exactly as it appears, making it easy to include multi-line text or code snippets.
⚙️

How It Works

A raw string in Kotlin is like writing a note on a piece of paper exactly as you want it to look, without worrying about special codes or symbols. Normally, strings need special characters like \n for new lines or \" for quotes inside them. But with raw strings, you just type everything as it is, including line breaks and quotes.

Think of it like a window where you can see the text inside without any filters or changes. This makes raw strings very useful when you want to include things like JSON, XML, or code snippets directly in your program without changing their format.

💻

Example

This example shows how to create a raw string with multiple lines and quotes without using escape characters.

kotlin
fun main() {
    val rawString = """
        Hello, this is a raw string.
        It can span multiple lines.
        """Quotes""" don't need to be escaped.
    """
    println(rawString)
}
Output
Hello, this is a raw string. It can span multiple lines. """Quotes""" don't need to be escaped.
🎯

When to Use

Use raw strings when you need to include text that has many special characters or spans multiple lines, such as:

  • Writing JSON or XML data directly in your code.
  • Including SQL queries without escaping quotes.
  • Adding multi-line messages or formatted text.
  • Embedding code snippets or regular expressions.

This saves time and makes your code cleaner and easier to read.

Key Points

  • Raw strings use triple quotes """ to start and end.
  • They preserve all characters exactly, including new lines and quotes.
  • No need to escape special characters inside raw strings.
  • Useful for multi-line text and complex string content.

Key Takeaways

Raw strings in Kotlin are enclosed in triple quotes and keep text exactly as typed.
They allow multi-line strings without escape characters for newlines or quotes.
Ideal for embedding JSON, XML, SQL, or formatted text directly in code.
Using raw strings makes code cleaner and easier to maintain when handling complex strings.