Kotlin String.plus()

Kotlin String.plus() Tutorial

The String.plus() function in Kotlin is used to concatenate this string with string representation of other object. It returns a new string that represents the concatenation of the original string with the provided input.

In this tutorial, we’ll explore the syntax of the String.plus() function and provide examples of its usage in Kotlin strings.

Syntax

The syntax of the String.plus() function is:

operator fun plus(
    other: Any?
): String

where

ParameterDescription
otherAn object.
Parameters of String.plus() function

the String.plus() function returns a string obtained by concatenating this string with the string representation of the given other object.

Examples for String plus() function

1. Concatenating Strings

In this example, we shall concatenate two strings using String.plus() function.

  1. Take a string value in string1.
  2. Take other string value in string2.
  3. Call plus() function on string1 and pass the string2 as argument. The function returns the concatenated string.
  4. You may print the returned string to the console output.

Kotlin Program

fun main() {
    val string1 = "Apple"
    val string2 = "Banana"

    // Using plus() to concatenate two strings
    val concatenatedString = string1.plus(string2)
    println("Concatenated String:\n$concatenatedString")
}

Output

Concatenated String:
AppleBanana

Summary

In this tutorial, we’ve covered the String.plus() function in Kotlin, its syntax, and how to use it to concatenate strings or any other data type. This function provides a concise and intuitive way to create a new string by combining multiple values.