Kotlin String toString()

Kotlin String toString()

The toString() function in Kotlin is used to obtain a string representation of the given object.

For strings themselves, calling toString() simply returns the original string. However, this function is commonly used to convert other data types to their string representations.

In this tutorial, we’ll explore the syntax of the toString() function and provide examples of its usage in Kotlin strings and other data types.

Syntax

The syntax of the toString() function is as follows:

fun toString(): String

The toString() function returns a string representation of the object.

Examples for String toString() function

1. Converting Other Data Types to Strings

In the following program, we take object of types Int, and Boolean, and convert them to String using toString() function.

Kotlin Program

fun main() {
    val number = 42
    val booleanValue = true

    // Using toString() to convert other data types to strings
    val numberString = number.toString()
    val booleanString = booleanValue.toString()

    // Printing the original values and their string representations
    println("Original Number: $number")
    println("Number as String: $numberString")
    println("Original Boolean: $booleanValue")
    println("Boolean as String: $booleanString")
}

Output

Original Number: 42
Number as String: 42
Original Boolean: true
Boolean as String: true

Summary

In this tutorial, we’ve covered the toString() function in Kotlin strings, its syntax, and how to use it to obtain string representations of objects. This function is particularly useful when you need to convert other data types to strings for display or logging purposes.