kotlin-types-strings.md

#Strings

Last modified: 04 February 2026

Strings in Kotlin are represented by the type String. On the JVM, an object of String type in UTF-16 encoding uses approximately 2 bytes per character.

Generally, a string value is a sequence of characters in double quotes ("):

kotlinval str = "abcd 123"

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:

kotlinfor (c in str) {
    println(c)
}

#Immutability

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:

kotlinval str = "abcd"

// Creates and prints a new String object
println(str.uppercase())
// ABCD

// The original string remains the same
println(str)
// abcd

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:

kotlinval s = "abc" + 1
println(s + "def")
// abc1def
Note: In most cases, using string templates or multiline strings is preferable to string concatenation.

#String literals

Kotlin has two types of string literals:

  1. Escaped strings
  2. Multiline strings

#Escaped strings

Escaped strings can contain escaped characters. Escaping is done with a backslash (\).

kotlinval s = "Hello, world!\n"

#Multiline strings

Multiline strings can contain newlines and arbitrary text. It is delimited by a triple quote ("""), contains no escaping, and can contain any other characters:

kotlinval text = """
    for (c in "foo")
        print(c)
    """

To remove leading whitespace from multiline strings, use the trimMargin() function. By default, a pipe symbol | is used as the margin prefix:

kotlinval text = """
    |Tell me and I forget.
    |Teach me and I remember.
    |Involve me and I learn.
    |(Benjamin Franklin)
    """.trimMargin()

#String templates

String literals may contain template expressions – pieces of code evaluated and concatenated into a string. A template expression starts with a dollar sign ($).

Variable name:

kotlinval i = 10
println("i = $i")
// i = 10

val letters = listOf("a","b","c","d","e")
println("Letters: $letters")
// Letters: [a, b, c, d, e]

Expression in curly braces:

kotlinval s = "abc"
println("$s.length is ${s.length}")
// abc.length is 3

To insert a literal dollar sign in a multiline string, use the following syntax:

kotlinval price = """
${'$'}_9.99
"""

#Multi-dollar string interpolation

Multi-dollar string interpolation allows you to specify how many consecutive dollar signs are required to trigger interpolation. This is useful when writing strings (like JSON or regex) that contain many literal dollar signs.

kotlinval KClass<*>.jsonSchema : String
    get() = $$"""
    {
      "$schema": "https://json-schema.org/draft/2020-12/schema",
      "$id": "https://example.com/product.schema.json",
      "$dynamicAnchor": "meta",
      "title": "$${simpleName ?: qualifiedName ?: "unknown"}",
      "type": "object"
    }
    """

In this example, the $$ prefix means $$ triggers interpolation, while single $ signs are treated as literal characters.


#String formatting

Note: String.format() is only available in Kotlin/JVM.

The String.format() function accepts a format string and arguments. Common specifiers include %d (integers), %f (floats), and %s (strings).

kotlin// Formats an integer with leading zeroes
val integerNumber = String.format("%07d", 31416)
println(integerNumber)
// 0031416

// Formats a float with a + sign and four decimal places
val floatNumber = String.format("%+.4f", 3.141592)
println(floatNumber)
// +3.1416

// Formats two strings to uppercase
val helloString = String.format("%S %S", "hello", "world")
println(helloString)
// HELLO WORLD

// Using argument_index to reference the same argument
val negativeNumberInParentheses = String.format("%(d means %1\$d", -31416)
println(negativeNumberInParentheses)
//(31416) means -31416