Efficiently managing multiline strings in Kotlin

Kotlin @ Freshers.in

Multiline strings are a common necessity in programming, especially when dealing with large amounts of text or complex string formats. Kotlin, a modern programming language, offers a robust and convenient way to handle multiline strings. This article provides an in-depth look into managing multiline strings in Kotlin, equipped with practical examples for a better understanding.

Writing a Multiline String:

Create a variable to hold your multiline string. For instance:

val greeting = """
    Hello,
    This is a message from Sachin.
    Have a great day!
""".trimIndent()

The trimIndent() function removes the leading whitespace from each line in the string.

Using multiline strings in real-world scenarios

Consider a scenario where David, a software developer, needs to embed SQL queries or JSON data within his Kotlin code. Multiline strings make this process seamless and readable:

val sqlQuery = """
    SELECT *
    FROM users
    WHERE name = 'David'
""".trimIndent()

val jsonData = """
    {
        "name": "Wilson",
        "age": 30,
        "city": "New York"
    }
""".trimMargin()

The trimMargin() function is particularly useful when you want to align your multiline string with a custom margin prefix, like |.

Advanced usage: String interpolation

Kotlin also supports string interpolation within multiline strings, allowing dynamic content:

val name = "Raju"
val age = 25

val userInfo = """
    Name: $name
    Age: $age years
""".trimIndent()

 

Author: user