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
In Kotlin, we use the $ character to interpolate a variable and ${} to interpolate an expression.
Character literals go in single quotes: '1' . Special characters start from an escaping backslash \ . The following escape sequences are supported: \t – tab.
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.
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.
Create a string, and invoke intention actions on it with Alt + Enter. Select Inject language or reference
, and then JSON
.
Use Alt + Enter again, and choose Edit JSON Fragment
.
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.
Escaping special chars in regular String
s, 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 String
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With