Strings
Strings in Kotlin are represented by the type String
. Generally, a string value is a sequence of characters in double quotes ("
):
Elements of a string are characters that you can access via the indexing operation: s[i]
. You can iterate over these characters with a for
loop:
Strings are immutable. Once you initialize a string, you can't change its value or assign a new value to it. All operations that transform strings return their results in a new String
object, leaving the original string unchanged:
To concatenate strings, use the +
operator. This also works for concatenating strings with values of other types, as long as the first element in the expression is a string:
String literals
Kotlin has two types of string literals:
Escaped strings
Escaped strings can contain escaped characters.
Here's an example of an escaped string:
Escaping is done in the conventional way, with a backslash (\
).
See Characters page for the list of supported escape sequences.
Raw strings
Raw strings can contain newlines and arbitrary text. It is delimited by a triple quote ("""
), contains no escaping and can contain newlines and any other characters:
To remove leading whitespace from raw strings, use the trimMargin()
function:
By default, a pipe symbol |
is used as margin prefix, but you can choose another character and pass it as a parameter, like trimMargin(">")
.
String templates
String literals may contain template expressions – pieces of code that are evaluated and whose results are concatenated into the string. A template expression starts with a dollar sign ($
) and consists of either a name:
or an expression in curly braces:
You can use templates both in raw and escaped strings. To insert the dollar sign $
in a raw string (which doesn't support backslash escaping) before any symbol, which is allowed as a beginning of an identifier, use the following syntax: