Chapter 4: Operators, Expressions & String Templates
Operators, Expressions & String Templates — this is where Kotlin starts feeling really magical and fun compared to Java!
We’re going to cover:
- All types of operators (arithmetic, comparison, logical, Elvis)
- Bitwise operations (they’re very different & cleaner in Kotlin)
- Smart casts (Kotlin’s superpower for type safety)
- String templates (one of the most loved features)
- Raw strings (multi-line strings without escape hell)
Like always, imagine we’re sitting together in a Bandra café — I’m going to explain everything super slowly, with real-life analogies, lots of copy-paste examples, step-by-step breakdowns, tables, common mistakes, and fun facts.
Grab your cutting chai ☕ — let’s go!
1. Arithmetic Operators (Same as Java, but Cleaner)
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 3 | 8 |
| – | Subtraction | 10 – 4 | 6 |
| * | Multiplication | 4 * 6 | 24 |
| / | Division | 10 / 3 | 3 (Int division) |
| % | Modulus (remainder) | 10 % 3 | 1 |
| ++ / — | Increment / Decrement | var x = 5; x++ | 6 |
Kotlin Bonus: You can use underscores for readability!
|
0 1 2 3 4 5 6 7 8 9 10 11 |
val bigNumber = 1_000_000_000L // 1 billion – easy to read! val taxRate = 18.0 val total = 85000 + 15000 // 100000 val afterTax = total * (1 - taxRate / 100) println("After 18% tax: $afterTax") // 69700.0 |
2. Comparison & Equality Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
| == | Structural equality (content) | “hello” == “hello” | true |
| != | Not equal | “hello” != “hi” | true |
| === | Referential equality (same object) | “hello” === “hello” | true (string pool) |
| !== | Not same object | — | — |
| > >= < <= | Greater / less than | age >= 18 | — |
Important difference from Java:
- == in Kotlin is always structural (calls equals())
- === is referential (same as Java’s ==)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
val a = "Kotlin" val b = "Kotlin" val c = String("Kotlin".toCharArray()) // New object println(a == b) // true (content same) println(a === b) // true (string pool) println(a == c) // true (content same) println(a === c) // false (different objects) |
3. Logical Operators (Same as Java)
| Operator | Meaning | Example |
|---|---|---|
| && | AND (both true) | (age >= 18) && (hasLicense) |
|
||
| ! | NOT | !isStudent |
Short-circuiting works the same: && stops if first is false || stops if first is true
4. Elvis Operator (?:) – Kotlin’s Null-Safe Superpower
The Elvis operator is written as ?: — named because it looks like Elvis’s hair! 😄
Syntax: expression ?: defaultValue
Meaning: If left side is not null → use it If left side is null → use right side
Real-life analogy: You ask your friend: “Do you have a pen?”
- If yes → give me the pen
- If no → give me a pencil (default)
Example:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
val name: String? = null val displayName = name ?: "Guest" // If name is null, use "Guest" println("Welcome, $displayName!") // Welcome, Guest! val email: String? = "webliance@example.com" val safeEmail = email ?: "no-email@provided.com" println(safeEmail) // webliance@example.com |
Common pattern – with safe call:
|
0 1 2 3 4 5 6 |
val length = nullableString?.length ?: 0 // If null → 0 |
5. Bitwise Operations (Very Different & Cleaner in Kotlin)
In Java → &, , ^, ~, <<, >>, >>> In Kotlin → infix functions (more readable!)
| Operation | Kotlin (infix) | Java Equivalent | Example |
|---|---|---|---|
| AND | and | & | 5 and 3 → 1 |
| OR | or | |
|
| XOR | xor | ^ | 5 xor 3 → 6 |
| NOT | inv() | ~ | 5.inv() → -6 |
| Left shift | shl | << | 5 shl 1 → 10 |
| Right shift (signed) | shr | >> | 5 shr 1 → 2 |
| Right shift (unsigned) | ushr | >>> | 5 ushr 1 → 2 |
Example:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
val a = 0b1010 // 10 in binary val b = 0b1100 // 12 println(a and b) // 8 (1000) println(a or b) // 14 (1110) println(a xor b) // 6 (0110) println(a shl 1) // 20 (10100) |
6. Smart Casts – Kotlin’s Magic Type Safety
Smart cast = compiler automatically knows the type after a null or type check.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
fun printLength(obj: Any?) { // Smart cast: after != null check, obj is automatically non-null String? if (obj is String) { println("Length: ${obj.length}") // No ! needed! } // Even better with safe call + let obj?.let { if (it is String) { println("Safe length: ${it.length}") } } } |
Another example:
|
0 1 2 3 4 5 6 7 8 9 |
val x: Any = "Hello" if (x is String) { println(x.uppercase()) // Smart cast: x is String } |
7. String Templates & Raw Strings
String Templates – super easy variable embedding
|
0 1 2 3 4 5 6 7 8 9 10 |
val name = "Webliance" val age = 25 val greeting = "नमस्ते $name! तुम्ही $age वर्षांचे आहात!" // Simple val future = "Next year तुम्ही ${age + 1} वर्षांचे व्हाल!" // Expression inside ${} println(greeting) |
Raw Strings – multi-line strings without escape characters
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
val html = """ <html> <body> <h1>Welcome to Kotlin</h1> <p>नमस्ते Webliance!</p> </body> </html> """.trimIndent() // Removes leading spaces println(html) |
trimMargin() – custom margin character
|
0 1 2 3 4 5 6 7 8 9 10 |
val sql = """ |SELECT * |FROM students |WHERE age > 20 """.trimMargin() // Uses | as margin |
Quick Recap Table (Your Cheat Sheet)
| Feature | Kotlin Way (Best Practice) | Java Equivalent (for comparison) |
|---|---|---|
| Immutable | val name = “Webliance” | final String name = “Webliance” |
| Mutable | var age = 25 | int age = 25 |
| String template | “Hello $name!” or ${age + 1} | “Hello ” + name + “!” |
| Raw string | “”” multi-line “”” | No direct equivalent |
| Elvis operator | name ?: “Guest” | name != null ? name : “Guest” |
| Smart cast | if (obj is String) { obj.length } | if (obj instanceof String) { ((String)obj).length() } |
| Bitwise | a and b, a or b, a shl 1 | a & b, `a |
Homework for You (Let’s Make It Fun!)
- Basic Declare val name = “Webliance” and var score = 85. Print: “नमस्ते $name! तुमचा स्कोअर $score आहे.”
- Medium Create a nullable String? email. Use Elvis to print “Email: $email” or “Email: no-email@provided.com” if null.
- Advanced Write a function fun describePerson(name: String?, age: Int?) that prints details using safe calls and Elvis.
- Fun Use raw string to print a nice formatted resume header.
- Challenge Fix this buggy code:
Kotlin01234567val message: String? = nullprintln(message.length) // Crash!
You’ve just mastered Kotlin’s core magic — null safety, smart casts, string templates, and clean operators!
