Skip to Content
Kotlin📘 Ngôn ngữ KotlinString Templates và Interpolation

String Templates và Interpolation trong Kotlin

1. Simple template - $variable

val name = "Alice" val age = 25 println("Hello, $name!") // Hello, Alice! println("I am $age years old") // I am 25 years old

2. Expression template - ${expression}

val a = 10 val b = 20 println("Sum: ${a + b}") // Sum: 30 println("Max: ${if (a > b) a else b}") // Max: 20

3. Template với properties

data class Person(val name: String, val age: Int) val person = Person("Bob", 30) println("${person.name} is ${person.age} years old")

4. Template với function calls

fun square(x: Int) = x * x val num = 5 println("Square of $num is ${square(num)}") // Square of 5 is 25

5. Escape $ symbol

val price = 100 println("Price: \$${price}") // Price: $100 // Hoặc dùng raw string println("""Price: ${'$'}$price""")

6. Multi-line templates

val name = "Alice" val items = listOf("Apple", "Banana", "Orange") val message = """ Hello, $name! You have ${items.size} items: ${items.joinToString(", ")} """.trimIndent() println(message)

7. Template với nullable

val name: String? = null println("Name: ${name ?: "Unknown"}") // Name: Unknown println("Length: ${name?.length ?: 0}") // Length: 0

8. Complex expressions

val numbers = listOf(1, 2, 3, 4, 5) println("Even numbers: ${numbers.filter { it % 2 == 0 }}") println("Sum: ${numbers.sum()}") println("Average: ${numbers.average()}")

9. Ví dụ thực tế: Format output

data class Product(val name: String, val price: Double, val quantity: Int) val products = listOf( Product("Laptop", 15000000.0, 2), Product("Mouse", 200000.0, 5) ) for (product in products) { println(""" Product: ${product.name} Price: ${"%,.0f".format(product.price)} VNĐ Quantity: ${product.quantity} Total: ${"%,.0f".format(product.price * product.quantity)} VNĐ """.trimIndent()) }

📝 Tóm tắt

  • $variable - Simple variable interpolation
  • $\{expression\} - Expression interpolation
  • \$ - Escape dollar sign
  • Có thể gọi functions, properties, expressions
  • Hoạt động với cả regular và raw strings
  • Kết hợp tốt với null safety operators
Last updated on