Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a string to a var without escape symbol in Kotlin?

I hope to pass the string {"name":"My Settings 1"} to a var aa

I have to write it using the code var aa=" {\"name\":\"My Settings 1\"} "

Is there a simple way in Kotlin when I use Android Studio 3.0 ?

I know <![CDATA[...]]> is good for XML content

like image 982
HelloCW Avatar asked Nov 16 '17 08:11

HelloCW


People also ask

What is ${} in Kotlin?

In Kotlin, we use the $ character to interpolate a variable and ${} to interpolate an expression.

How do you escape the special characters in Kotlin?

Character literals go in single quotes: '1' . Special characters start from an escaping backslash \ . The following escape sequences are supported: \t – tab.

How do I create a string variable in Kotlin?

To declare a string in Kotlin, we need to use double quotes(” “), single quotes are not allowed to define Strings. Creating an empty String: To create an empty string in Kotlin, we need to create an instance of String class.


2 Answers

The simplest thing you can do in Kotlin is use raw strings with triple quote marks:

val a = """{"name":"My Settings 1"}"""

For a tooling solution instead of a language solution (so this works both in Kotlin and Java), you can use language injection in Android Studio or IntelliJ.

  1. Create a string, and invoke intention actions on it with Alt + Enter. Select Inject language or reference, and then JSON.

    Inject language or reference

    JSON

  2. Use Alt + Enter again, and choose Edit JSON Fragment.

    Edit JSON Fragment

  3. Edit the raw JSON in the panel that appears on the bottom, and IntelliJ will automatically mirror its contents into the string, escaping any characters that have to be escaped.

    Screenshot of the JSON fragment editor

like image 149
zsmb13 Avatar answered Oct 14 '22 13:10

zsmb13


Escaping special chars in regular Strings, like in your example, is what has to be done with Java and also Kotlin:

"{\"name\":\"My Settings 1\"}"

Kotlin offers raw Strings to evade this. In these raw Strings there's no need to escape special chars, which shows the following:

 """{"name":"My Settings 1"}"""

Raw Strings are delimited by a triple quote ("""). Read the docs here.

like image 42
s1m0nw1 Avatar answered Oct 14 '22 13:10

s1m0nw1