Raw Strings , how are these different from escaped strings and where should be use these
Asked Answered
R

4

11

As per my research,

Kotlin has two types of string literals:-

Escaped strings that may have escaped characters in them .

val s = "Hello ,World\n" +
    "from escaped string\n"+
    "kotlin"

Raw string is delimited by a triple quote ("""), contains no escaping and can contain newlines and any other characters:

val m = """Hello, World
       |from raw string
       |kotlin """.trimMargin()

These strings can be used in multi lines without the need to concatenate each line and an without escaping.

Do we use raw strings only for simplicity and easy implementation or do these offer some better performance in any case?

And are these any other use-cases where we should consider using raw strings?

Ric answered 20/9, 2018 at 6:22 Comment(1)
Do we use raw strings only for simplicity and easy implementation? generally yes.Phyllome
K
7

Your answer is well explained here at this website. I am going to include only essential part of it here.

String in Kotlin can be used in multiple ways as described in the above link. It is purely depends upon the requirement for which to use. If you have extra large string like html page etc then you can go with Raw string delimited by triple quote ("""). And in where you have short strings then you could use Escaped strings.

There is no real performance difference between these but depends upon how much string concatenation you are using while building values in it.

Kathikathiawar answered 20/9, 2018 at 7:51 Comment(0)
W
3

I don't know about any performance difference between the two string literal types, but there is at least one interesting use case where you should consider using raw strings: regular expressions.

Predefined character classes and many other constructs in regular expressions are introduced by a \ character (e.g. \s to match a whitespace character). When including those in a string, you need to escape them: so, for any such character in a regular expression, you need to write two, such as "\\d" to match a single digit.

However, raw strings allow you to skip the escaping part, leading to cleaner and slighlty more concise regular expressions than those you would write when your only string literal type is escaped, as it happens in Java.

Note that raw strings are not a new concept or an idea introduced by Kotlin. For example, Python has had them for a long time.

Walkabout answered 20/9, 2018 at 7:45 Comment(1)
Similar in vein, would be cases where it would be otherwise necessary to escape the dollar-sign '$' to avoid the interpolation.Honan
L
2

Use-case: query syntax coloring in Room queries

With Kotlin's raw strings you can write queries on multiple lines in Room's Dao, example:

@Dao
interface HappyDao {
    @Query(
            """
            SELECT
            One,
            Two,
            Three
            FROM MYTABLE
            """
    )
    fun getAll(): List<MyObject>
}

And still have the syntax coloring of the Room validator as if you are writing everything on one line (along with alerts on query syntax errors during code writing). It is especially very useful with long queries, with many fields or joins.

Without raw strings it would be like this:

@Dao
interface HappyDao {
    @Query(
            "SELECT" +
            "One," +
            "Two," +
            "Three" +
            " FROM MYTABLE"
    )
    fun getAll(): List<MyObject>
}

and it would not benefit of Room's syntax coloring.

Lightness answered 9/4, 2019 at 15:21 Comment(0)
S
0

How do normal string literals work?

In Kotlin, normal string literals are enclosed in pairs of single double quotes: "like this". Characters like line break, backslash \ and double quotes " work as special syntax and can't enter the string verbatim, so in order to include them we often have to write escape sequences: \n, \\, \".

How do raw string literals work?

In Kotlin, raw string literals are enclosed in pairs of triple double quotes: """like this""". Raw string literals don't have escape sequences, instead they allow you to verbatim write characters that would otherwise work as special syntax. Oh, except for dollar sign syntax for string interpolation — more on that later.

When to consider raw string literals?

Raw string literals can be very convenient for writing formatted output that has line breaks, backslashes and quote marks, for example, text file data output or interactive text menus. In fact, any text could be sophisticated enough that escaping each special character would be detrimental to its readability.

Example:

print("""Hello, $username, welcome to "File Shredder 3000"!
Please input the "path\to\file_or_directory" that you wish to shred:
C:\Users\$username\""")

When to always use raw string literals?

It's worth noting that from time to time we have to write code in RegEx, SQL, JavaScript, HTML, or any other language — that lives inside string literals within our Kotlin code. This is where raw strings really shine and are absolutely a necessity — language injections. Here raw strings provide a way to write inner syntax without being bothered by outer syntax. Even if your language injection doesn't contain special characters, it might be a good idea to write them as raw string literals in advance, just in case such characters will be added in future changes, to avoid syntactic and semantic errors in injected code.

Example*:

val textNodeRe = Regex("""(?:^|>)(.*?)(?:<|$)""", setOf(MULTILINE, DOT_MATCHES_ALL))
val openingTagRe = Regex("""<(\w+).*?>""")
val closingTagRe = Regex("""</(\w+).*?>""")
val openingAnchorTagRe = Regex("""<a.*?href="(.+?)".*?>""")
val closingAnchorTagRe = Regex("""</(a).*?>""")

What's the catch?

There is a catch with raw string literals. They still support string interpolation using the dollar sign $ syntax, and since raw string literals don't have escape sequences, writing a word prefixed by a dollar sign requires a verbose and hacky workaround: """${"$"}like this""". And of course, being the boundary of the raw string literal, the triple double quotes """ also require similar treatment to be included: """${"\"\"\""}""".

Sondra answered 18/6 at 13:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.