Kotlin Multiline Strings 🎯

beginner
9 min

Kotlin Multiline Strings 🎯

Welcome back to CodeYourCraft! Today, we're diving into Kotlin's multiline strings. This tutorial is perfect for beginners and intermediates. Let's get started! 🚀

What are Multiline Strings? 📝

In Kotlin, multiline strings are a way to write multi-line text without the hassle of escape characters. They are enclosed between triple quotes (""" " """).

kotlin
val multilineString = """ This is a multiline string. It can contain multiple lines. And even indented text! """

Why Multiline Strings? 💡

Multiline strings make our code cleaner and easier to read. They eliminate the need for the backslash (\) and the newline character (\n) commonly used in single-line strings for multi-line text.

Using Multiline Strings 🎯

You can use multiline strings in your code just like single-line strings. You can concatenate them, perform string interpolation, and even assign them to variables.

Example 1: Concatenating Multiline Strings 📝

kotlin
val firstLine = """Hello, World!""" val secondLine = """This is line 2.""" val finalString = "$firstLine\n$secondLine" println(finalString) // Output: Hello, World! // This is line 2.

Example 2: String Interpolation with Multiline Strings 📝

kotlin
val name = "Alice" val greeting = """ Hello, $name! Welcome to CodeYourCraft! """ println(greeting) // Output: Hello, Alice! // Welcome to CodeYourCraft!

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

What is a Kotlin multiline string?

That's it for today! In the next lesson, we'll dive deeper into Kotlin strings and explore more features. See you then! 🤝

Happy coding! 🚀