โ””โ”€โ”€ README.md /README.md: -------------------------------------------------------------------------------- 1 | # 100 Important Kotlin Interview Questions in 2025 2 | 3 |
4 |

5 | 6 | web-and-mobile-development 7 | 8 |

9 | 10 | #### You can also find all 100 answers here ๐Ÿ‘‰ [Devinterview.io - Kotlin](https://devinterview.io/questions/web-and-mobile-development/kotlin-interview-questions) 11 | 12 |
13 | 14 | ## 1. What is _Kotlin_ and how does it interoperate with _Java_? 15 | 16 | **Kotlin** is a modern, statically typed language. Having been developed by JetBrains, it targets the JVM, among other platforms. 17 | 18 | ### Key Strengths of Kotlin on JVM 19 | 20 | - **Concise Syntax**: Kotlin's compact code minimizes boilerplate. 21 | - **Null Safety**: With its nullable types, Kotlin helps reduce null-pointer exceptions. 22 | - **Extension Functions**: These functions simplify class extension. 23 | - **Coroutines**: Kotlin's lightweight threads make asynchronous operations more manageable. 24 | - **Immutability**: Kotlin has built-in support for immutable structures through 'val'. 25 | 26 | ### Core Java-Kotlin Interoperability Mechanisms 27 | 28 | **Kotlin** can use Java Frameworks and libraries. Plus, it offers mechanisms for both Java-to-Kotlin and Kotlin-to-Java interoperability. 29 | 30 | These mechanisms include: 31 | 32 | 1. **Kotlin Libraries and Frameworks**: They are tested to work with Java. 33 | 2. **nullability Roadmap and @Nullable/@NotNull Annotations**: One can take advantage of both Kotlin's null-safe types and Java's nullability guidelines. 34 | 3. **Supportive Native Tools**: Kotlin paves the way for Android development with libraries compatible with Java. 35 | 4. **Instrumented and Standard Libraries**: Both libraries have Kotlin origin. It offers the convenience of unifying coding styles and tools. The 'kotlin.jvm' package is tailored for standard Java operations. 36 | 37 | ### Common Scenarios for Java-Kotlin Interoperability 38 | 39 | - **Migrating Codebases**: Gradual transitions are possible. Both languages can interoperate within a single project. 40 | 41 | - **Collaborative Development**: Team members who prefer different languages can still contribute to the common codebase. 42 | 43 | - **Libraries and Frameworks**: Leveraging Java libraries in a Kotlin-based system is seamless. 44 | 45 | - **Android Development**: Kotlin has been officially backed by Google as a primary language for Android app development. 46 | 47 | - **VM and Platform Independence**: Kotlin's multi-platform capabilities allow functionality sharing across different platforms. 48 | 49 | ### Java-Kotlin Code Example: Interoperability 50 | 51 | Here is the Java class: 52 | 53 | ```java 54 | public class Fruit { 55 | private String name; 56 | private int quantity; 57 | 58 | public Fruit(String name, int quantity) { 59 | this.name = name; 60 | this.quantity = quantity; 61 | } 62 | 63 | public String getName() { 64 | return name; 65 | } 66 | 67 | public int getQuantity() { 68 | return quantity; 69 | } 70 | 71 | public void setName(String name) { 72 | this.name = name; 73 | } 74 | 75 | public void setQuantity(int quantity) { 76 | this.quantity = quantity; 77 | } 78 | } 79 | ``` 80 | 81 | And here is the Kotlin class that uses the `Fruit` Java class: 82 | 83 | ```kotlin 84 | fun main() { 85 | val apple = Fruit("Apple", 10) // Use of Java class 86 | println("Name: ${apple.name}, Quantity: ${apple.quantity}") 87 | 88 | apple.name = "Green Apple" // Kotlin syntax for modifying Java object 89 | apple.quantity += 5 90 | 91 | println("Updated Apple: Name - ${apple.name}, Quantity - ${apple.quantity}") 92 | } 93 | ``` 94 |
95 | 96 | ## 2. How does _Kotlin_ improve upon _Java_ for _Android development_? 97 | 98 | **Kotlin**, a statically-typed language, provides several benefits over Java in the context of Android development. 99 | 100 | ### Improved Developer Experience 101 | 102 | - **Intuitive Syntax**: Kotlin reduces boilerplate code, leading to more elegant, succinct, and readable codebases. 103 | - **Extension Functions**: This language feature allows developers to extend specific types with new functionalities. 104 | 105 | ### Enhanced Productivity 106 | 107 | - **Null Safety**: The type system in Kotlin differentiates between nullable and non-nullable references, effectively reducing `NullPointerException` occurrences. 108 | - **Smart Casting**: The language's type inference allows automatic casting of types wherever possible, thereby eliminating the need for explicit casting. 109 | - **Coroutines**: Kotlin's built-in support for coroutines makes asynchronous programming simpler and less error-prone. 110 | 111 | ### Modern Language Features 112 | 113 | - **Lambdas**: Kotlin's support for concise yet powerful lambda expressions outstrips that of Java. 114 | - **Data Classes**: These classes, which Kotlin can generate getters, setters, `equals()`, and other basic methods automatically make working with models more streamlined. 115 | - **Type Inference**: The language can often discern the type of a variable from its value, thus alleviating the need for explicit type declarations. 116 | 117 | ### Compatibility with Java 118 | 119 | - **Interoperability with Java**: Kotlin integrates seamlessly with existing Java code, allowing for easy migration and coexistence. 120 | - **Full Java SDK Support**: Kotlin is fully compatible with the Java SDK, enabling access to the plethora of Java libraries from Kotlin projects. 121 | 122 | ### Enhanced Safety and Accuracy 123 | 124 | - **Immutability by Default**: In Kotlin, variables are, by default, immutable (read-only). This approach is conducive to preventing bugs and improving code safety. 125 | - **Parameterized Contracts**: The `where` clause in Kotlin ensures more robust compile-time checks for generic types. 126 | - **Range and Step Constructs**: These features enhance data accuracy and prevent out-of-bounds access. 127 |
128 | 129 | ## 3. What are the basic types in _Kotlin_? 130 | 131 | **Kotlin** has a rich set of built-in data types tailored for various uses. They are mostly categorized into **Primitive** and **Object** data types. 132 | 133 | ### Basic Types Categories 134 | 135 | #### **Primitive Types** 136 | 137 | **Kotlin** introduces the following **Primitive** types: 138 | - `Double`: Double precision 64-bit floating point number. 139 | - `Float`: Single precision 32-bit floating point number. 140 | - `Long`: 64-bit integer. 141 | - `Int`: 32-bit integer. 142 | - `Short`: 16-bit integer. 143 | - `Byte`: 8-bit integer. 144 | - `Char`: A single 16-bit Unicode character. 145 | - `Boolean`: Represents truth values: true or false. 146 | 147 | #### **Object Types** 148 | 149 | These are **Object** types: 150 | 151 | - `String`: A sequence of characters. 152 | - `Any`: The root of the Kotlin class hierarchy. This is the equivalent of `Object` in Java. 153 | 154 | #### Other Types 155 | 156 | - `Array`: A class for array types. 157 | - `Function`: A function type, which is determined by its parameter types and return type. 158 | 159 | You can have a look at the Kotlin code. 160 | 161 | Here is the Kotlin code: 162 | 163 | ### Code Example: Kotlin Types 164 | 165 | ```kotlin 166 | fun main() { 167 | val doubleNum: Double = 100.0 168 | val floatNum: Float = 100.0f 169 | val longNum: Long = 100 170 | val intNum: Int = 100 171 | val shortNum: Short = 100 172 | val byteNum: Byte = 100 173 | val charLetter: Char = 'A' 174 | val isRainingToday: Boolean = true 175 | val text: String = "Hello, Kotlin!" 176 | 177 | val anyValue: Any = "This is an example of Any type in Kotlin" 178 | 179 | val intArray: Array = arrayOf(1, 2, 3, 4, 5) 180 | val strArray: Array = Array(5) { "Item #$it" } 181 | 182 | fun myFunction(num: Int): Boolean { 183 | return num % 2 == 0 184 | } 185 | 186 | val myFunctionType: (Int) -> Boolean = ::myFunction 187 | } 188 | ``` 189 |
190 | 191 | ## 4. Explain the difference between `val` and `var` in _Kotlin_. 192 | 193 | In Kotlin, the keywords `val` and `var` are used for **variable declaration**, each with distinct mutability characteristics. 194 | 195 | ### Immutable with `val` 196 | 197 | `val`, akin to `final` in Java, denotes an **immutable reference**. This means after its initial assignment, the reference doesn't change. However, the state of the object or type it points to can still be altered. 198 | 199 | ### Mutable with `var` 200 | 201 | `var` designates a **mutable reference**. This type of variable allows both reassignment and potential state changes during its lifecycle. 202 | 203 | ### Tips for Usage 204 | 205 | - **Prefer `val`**: Use it unless there's a compelling reason for mutability. This practice aligns with Kotlin's design for immutability. 206 | 207 | - **Mutable Limited**: In production code, restrict mutability with `var` to situations where its necessity is clear and justified. 208 | 209 | ### Code Example: `val` and `var` 210 | 211 | Here is the Kotlin code: 212 | 213 | ```kotlin 214 | fun main() { 215 | val PI = 3.14159 // Immutable PI, defined with val 216 | var count = 0 // Mutable count, defined with var 217 | 218 | // Following lines lead to compiler errors 219 | PI = 3.14 // Cannot reassign PI as it's declared with val, not var 220 | count = 1 // OK! Reassignment of a variable defined with var is allowed 221 | } 222 | ``` 223 |
224 | 225 | ## 5. How do you create a _singleton_ in _Kotlin_? 226 | 227 | In Kotlin, defining a **singleton** is straightfoward; the language provides a dedicated `object` keyword. 228 | 229 | When you declare a companion object in a class, it becomes a singleton accessible through the class name. This is useful for creating global handles. 230 | 231 | ### Singleton Using `object` Keyword 232 | 233 | - **Kotlin Code**: 234 | 235 | ```kotlin 236 | object MySingleton { 237 | fun someFunction() { 238 | // Logic here 239 | } 240 | } 241 | ``` 242 | 243 | - **Access**: 244 | 245 | ```kotlin 246 | MySingleton.someFunction() 247 | ``` 248 | 249 | ### Singleton through `Companion Object` 250 | 251 | - **Kotlin Code:** 252 | 253 | ```kotlin 254 | class MySingletonClass { 255 | companion object { 256 | fun someFunction() { 257 | // Logic here 258 | } 259 | } 260 | } 261 | ``` 262 | 263 | - **Access**: 264 | 265 | ```kotlin 266 | MySingletonClass.someFunction() 267 | ``` 268 | 269 | ### Why Use `object` over `companion object`? 270 | 271 | If a class doesn't require an instance or has a single instance throughout the application, `object` is the most succinct and expressive solution. 272 | 273 | In contrast, `companion object` is suitable when non-static methods or properties need to interact with the singleton. It's pertinent to classes you instatiate but have a single instance for per application. 274 | 275 | ### `object` Versus Traditional Singletons 276 | 277 | Kotlin's `object` offers several advantages over **traditional singletons**, including automatic management of thread safety, lazy initialization, and streamlined syntax. It's a recommended approach for modern Kotlin development. 278 | 279 | Traditional Java singletons also had complications with lazy initialization and thread safety, which are non-issues with Kotlin's `object`. 280 | 281 | From a design standpoint, the single-responsibility principle should guide the decision to use singletons. Cohesiveness allows for consistency and predictability across the app. 282 | 283 | ### Key Takeaways: 284 | 285 | - Kotlin's `object` keyword is the most straightforward way to create singletons. 286 | - `companion object` is appropriate for singletons tied to the containing class where both need to be instantiated. 287 | - Kotlin's `object` is a modern, expressive alternative to the verbosity and potential issues of traditional Java singletons. 288 | - Threading and resource management are handled seamlessly, simplifying code. 289 |
290 | 291 | ## 6. What are the _Kotlin type inference_ rules? 292 | 293 | Kotlin **type inference** represents a powerful feature that automatically determines variable types. Nonetheless, it does so within the constraints of **Kotlin's Type Hierarchy**. 294 | 295 | - Kotlin types are static, meaning they're determined at compile time. 296 | - The Kotlin compiler analyses assignments and method calls to infer types. 297 | - When there are multiple possible types, the compiler selects the most specific one. In case of ambiguity, the code will not compile, and a **type annotation** is needed to provide clarity. 298 | 299 | Kotlin also supports **type inference** with: 300 | 301 | - **Lambda expressions** 302 | - **Generics** 303 | 304 | The Kotlin compiler uses both the **expected type** and the **inferred type of the arguments** to infer the type of both return value and the arguments of the `run` and 'let' extension function. 305 | 306 | ### Type Inference With Lambdas 307 | 308 | In Kotlin, you can use `it` as shorthand for a single lambda parameter. Type inference deduces the type based on the context in which the lambda is used. 309 | 310 | The `list` argument is expected to be a list of strings, allowing `it` to be inferred as a `String`. Consequently, the type of `length` is inferred as `Int`. 311 | 312 | #### Code Example: Type Inference With Lambdas 313 | 314 | Here is the Kotlin code: 315 | 316 | ```kotlin 317 | fun main() { 318 | val names = listOf("Alice", "Bob") 319 | 320 | // Infers `it` as String 321 | val lengths: List = names.map { it.length } 322 | 323 | println(lengths) // Output: [5, 3] 324 | } 325 | ``` 326 |
327 | 328 | ## 7. Can _Kotlin code_ be executed without a `main` function? 329 | 330 | While it is essential to have a `main` function to initiate an application in most programming languages, **Kotlin** offers the flexibility to apply direct execution to standalone code. 331 | 332 | ### Direct Execution in Kotlin 333 | 334 | The directive to execute code without a `main` function is termed **script mode** and is enabled using the following steps: 335 | 336 | 1. Define a build and execution environment through the Kotlin compiler or the IntelliJ IDEA. 337 | 2. Ensure that the script file has **.kts** or **kotlin-script** extension to indicate it's a Kotlin script. 338 | 339 | This adaptation simplifies rapid prototyping and facilitates learning and testing in sandbox environments. Nonetheless, it's important to note that traditional Java applications, as well as Android applications, still necessitate a `main` function. 340 |
341 | 342 | ## 8. What is the purpose of the `Unit` type in _Kotlin_? 343 | 344 | While some languages use "void" to indicate functions or expressions with no useful return value, **Kotlin** leverages the Unit type. 345 | 346 | ### Why Kotlin Introduced 'Unit' 347 | 348 | The driving principle behind introducing the `Unit` type was to provide a unified approach to functions across the **object-oriented** and **functional** programming paradigms. 349 | 350 | ### Key Characteristics of `Unit` 351 | 352 | - **Singleton Element**: `Unit` is a singleton, meaning there's only one instance of it. This allows functions with **no explicit return** to be understood as returning a single, distinct value. 353 | - **Immutable State**: As a singleton, `Unit` is inherently immutable, ensuring that every function call returning `Unit` produces the same fixed value. 354 | 355 | ### Use Cases 356 | 357 | 1. **Functionality Communication**: `Unit` serves as a clear signal that a function is invoked strictly for its side effects. 358 | 2. **Interface Alignment**: Codebases aiming for consistency can utilize `Unit` to harmonize function return types. 359 | 360 | ### Code Example: Unit in Functions 361 | 362 | Here is the Kotlin code: 363 | 364 | ```kotlin 365 | // Function with explicit Unit return type 366 | fun greet(name: String): Unit { 367 | println("Hello, $name!") 368 | } 369 | 370 | // Function without explicit return type defaults to Unit 371 | fun performTask(): Unit { 372 | // Task logic goes here 373 | } 374 | 375 | // Function with no explicit return type 376 | fun noReturn(): Nothing? { 377 | // Code that will never execute 378 | throw NotImplementedError() 379 | } 380 | 381 | fun main() { 382 | // All three function calls here can be understood as returning Unit 383 | greet("Alice") 384 | performTask() 385 | println(noReturn()) // Will not print anything 386 | } 387 | ``` 388 | 389 | In this code, `greet("Alice")`, `performTask()`, and `println(noReturn())` are all implicitly equated to `Unit` return types. The "MessageBox" would close after 12 seconds without the output. 390 |
391 | 392 | ## 9. How do you perform _string interpolation_ in _Kotlin_? 393 | 394 | In Kotlin, you can **interpolate** strings using the `$` symbol. This mechanism allows for the direct embedding of variables, expressions, and Math operations within a string. 395 | 396 | Alternatively, you can leverage **raw strings** with the `trimMargin` method for multi-line text. 397 | 398 | ### Code Example: String Interpolation 399 | 400 | Here is the Kotlin code: 401 | 402 | ```kotlin 403 | fun main() { 404 | val name = "Alice" 405 | val age = 25 406 | 407 | println("Name: $name, Age: $age") 408 | 409 | // Dollar sign within a string 410 | println("$$100: A Hundred Dollars") 411 | 412 | // Interpolated expression 413 | val tripleAge = age * 3 414 | println("In 3 years, $name will be ${age + 3} years old, and 3 times $age is $tripleAge") 415 | 416 | // Raw string with trimMargin 417 | val poem = """ 418 | |Two roads diverged in a yellow wood, 419 | |And sorry I could not travel both 420 | |And be one traveler 421 | """.trimMargin() 422 | println(poem) 423 | } 424 | ``` 425 | 426 | ### Output 427 | 428 | ``` 429 | Name: Alice, Age: 25 430 | $100: A Hundred Dollars 431 | In 3 years, Alice will be 28 years old, and 3 times 25 is 75 432 | Two roads diverged in a yellow wood, 433 | And sorry I could not travel both 434 | And be one traveler 435 | ``` 436 |
437 | 438 | ## 10. What are _extension functions_ in _Kotlin_? 439 | 440 | **Kotlin's extension functions** provide a convenient mechanism for adding methods to existing classes without altering their source code. This is especially useful for extending classes that are otherwise fixed or derive from external libraries, such as built-in types from Java. 441 | 442 | ### Benefits of Extension Functions 443 | 444 | - **Improved Readability**: Extension functions enable adding context-specific methods to types. 445 | 446 | - **Consistent Naming**: These functions ensure a standard naming convention for classes. 447 | 448 | - **No Inheritance Issues**: Overriding is not a concern, making extension functions ideal for providing custom behavior to existing classes. 449 | 450 | - **Modular Code**: Associates utility methods directly with the classes they operate on, streamlining code organization. 451 | 452 | ### Function vs. Method 453 | 454 | In Kotlin, the term **"function"** typically refers to a top-level function, whereas the term **"method"** is used within the context of a class. 455 | 456 | ### Usage 457 | 458 | 1. **Importing Extension Functions**: Kotlin's standard library provides numerous extension functions. Additional extensions can be imported using the `import` directive. 459 | 460 | 2. **Working with Nullable Types**: Extension functions can be applied to nullable types to avoid invoking methods on `null`. By checking for `null` within the function, it ensures safe execution. 461 | 462 | 3. **Scoping**: Although extension functions resemble regular methods, their scoping is limited to the file where they are defined unless they are imported or are part of the same package. 463 | 464 | 4. **Inheritance**: When a class and its parent provide methods of the same name and signature, the class's own methods always take precedence. 465 | 466 | However, even when an extension function exists, classes and their derived types (e.g., subclasses) can override the functionality by defining methods with the same signature. 467 | 468 | ### Code: Extension Function on Nullable Type 469 | 470 | Here is the Kotlin code: 471 | 472 | ```kotlin 473 | fun String?.isNullEmptyOrBlank(): Boolean { 474 | return this == null || this.isEmpty() || this.isBlank() 475 | } 476 | 477 | fun main() { 478 | val text: String? = "Hello" 479 | val emptyText: String? = "" 480 | val blankText: String? = " " 481 | 482 | println(text.isNullEmptyOrBlank()) // false 483 | println(emptyText.isNullEmptyOrBlank()) // true 484 | println(blankText.isNullEmptyOrBlank()) // true 485 | } 486 | ``` 487 | In this example, `String?` is a nullable type, and the extension function **`isNullEmptyOrBlank`** checks for `null`, an empty string, or a string consisting entirely of whitespace. 488 |
489 | 490 | ## 11. How are `if` expressions used in _Kotlin_ as compared to _Java_? 491 | 492 | While both Kotlin and Java use `if` **expressions** to conditionally execute code, Kotlin offers more power and flexibility with its `if` expression. 493 | 494 | ### Key Differences 495 | 496 | - **Return Type**: In Java, you can only use `if` to conditionally execute statements. In contrast, Kotlin's `if` can also return a value, similar to the Ternary Operator in Java. 497 | 498 | - **Immutability**: Kotlin's `if` is an expression that produces a value, and that value is immutable once assigned. However, in Java, variables assigned within each `if` block can have different values outside the block. 499 | 500 | - **When to Use**: In Kotlin, the standard recommendation is to use `if` for simple or limited cases and use `when` for more complex and multifaceted scenarios. 501 | 502 | #### Example: If-Else Expression 503 | 504 | Here is the Kotlin code: 505 | 506 | ```kotlin 507 | val result = if (condition) "Value1" else "Value2" 508 | ``` 509 | 510 | And here is the equivalent Java code: 511 | 512 | ```java 513 | String result; 514 | if (condition) { 515 | result = "Value1"; 516 | } else { 517 | result = "Value2"; 518 | } 519 | ``` 520 | 521 | ### Best Practices 522 | 523 | - **Kotlin Compactness**: Utilize Kotlin's concise syntax for improved readability and maintainability. 524 | 525 | - **Type Inference**: In Kotlin, you may let the compiler infer the result type rather than explicitly defining it. 526 |
527 | 528 | ## 12. Explain `when` expressions in _Kotlin_. 529 | 530 | In **Kotlin**, the `when` expression is a powerful control-flow construct that simplifies and enhances many operations. 531 | 532 | It combines the best aspects of **conditional execution** and **pattern matching** from other languages like Java, C++, and Scala. This dynamic construct allows for complex evaluations in a concise, easy-to-read structure. 533 | 534 | ### Key Features 535 | 536 | - **Branching**: Similar to `switch` statements, `when` evaluates different conditions and triggers corresponding code blocks. 537 | - **Expression-based**: It works well in both code blocks and as standalone expressions. 538 | - **Versatile Syntax**: It supports a broad range of matching techniques, such as value matching, range checks, and null safety operators. 539 | - **Extensive Filtering**: Can evaluate conditions like type checks, boolean expressions, and custom checks. 540 | - **Sealed Classes Support**: Seamlessly integrates with sealed classes, enforcing a comprehensive check of all possible subtypes. 541 | 542 | ### Code Example: Basic when-expression 543 | 544 | Here is the Kotlin code: 545 | 546 | ```kotlin 547 | fun describe(object: Any): String { 548 | return when (object) { 549 | 1 -> "One" 550 | 2 -> "Two" 551 | 3, 4 -> "Three or Four" 552 | is String -> "That's a string" 553 | is Number -> "That's a number" 554 | else -> "Something else" 555 | } 556 | } 557 | 558 | fun main() { 559 | println(describe(1)) 560 | println(describe(3)) 561 | println(describe(5)) 562 | println(describe("hello")) 563 | } 564 | ``` 565 | 566 | When you run the above code, you will get the following output: 567 | 568 | ```plaintext 569 | One 570 | Three or Four 571 | Something else 572 | That's a string 573 | ``` 574 | 575 | ### Code Example: Returning Booleans 576 | 577 | Here is the Kotlin code: 578 | 579 | ```kotlin 580 | fun isStringOrEmpty(input: Any?): Boolean { 581 | return when (input) { 582 | null -> true 583 | is String -> input.isEmpty() 584 | else -> false 585 | } 586 | } 587 | 588 | fun main() { 589 | println(isStringOrEmpty(null)) 590 | println(isStringOrEmpty("")) 591 | println(isStringOrEmpty(123)) 592 | } 593 | ``` 594 | 595 | When you run the above code, you will get the following output: 596 | 597 | ```plaintext 598 | true 599 | true 600 | false 601 | ``` 602 | 603 | ### Advanced Example: Data Classes and Smart Casting 604 | 605 | Here is the Kotlin code: 606 | 607 | ```kotlin 608 | data class Person(val name: String, val age: Int, val email: String = "") 609 | 610 | fun processPerson(person: Person) { 611 | when { 612 | person.age < 0 -> println("Invalid age!") 613 | person.name.isBlank() -> println("No name provided") 614 | person.email.isBlank() -> println("No email provided") 615 | else -> { 616 | println("All details provided:") 617 | println("Name: ${person.name}") 618 | println("Age: ${person.age}") 619 | println("Email: ${person.email}") 620 | } 621 | } 622 | } 623 | 624 | fun main() { 625 | val person1 = Person("Alice", 25, "alice@example.com") 626 | 627 | val person2 = Person("Bob", 30) 628 | 629 | val person3 = Person("", -10, "invalidemail") 630 | 631 | processPerson(person1) // Should print all details 632 | processPerson(person2) // Should print "No email provided" 633 | processPerson(person3) // Should print "Invalid age!" 634 | } 635 | ``` 636 | 637 | - We define a data class, `Person`. 638 | - The `when` block operates without an explicitly defined expression (commonly referred to as a "subject"). This feature allows for more intricate conditions and is known as a "subject-less `when`." 639 |
640 | 641 | ## 13. How does _Kotlin_ handle _null safety_ and what is the _Elvis operator_? 642 | 643 | In Kotlin, **null safety** is a core feature designed to address the issues around null references. It aims to reduce `NullPointerException` errors that are commonly encountered in other languages, particularly Java. 644 | 645 | The **Elvis Operator** provides a concise means for handling `null` values within expressions. 646 | 647 | ### Null Safety 648 | 649 | Kotlin employs a set of rules to manage nullability in objects: 650 | 651 | #### Nullable Types 652 | 653 | - A type is marked as **nullable** if it can accept `null` values. This is indicated by appending `?` to the type name. 654 | 655 | ```kotlin 656 | val name: String? = null // Nullable String 657 | ``` 658 | 659 | - If the `name` variable was not marked as nullable (e.g., `val name: String = null`), and you attempted to assign `null`, the Kotlin compiler wouldn't allow it. 660 | 661 | #### Safe Calls 662 | 663 | - To invoke a method or access a property on a nullable object, use the **safe call** operator `?.`. The method is called only if the object isn't `null`: 664 | 665 | ```kotlin 666 | val length: Int? = name?.length // null if name is null 667 | ``` 668 | 669 | #### The Not-Null Assertion Operator 670 | 671 | - When you're certain an object isn't `null`, you can use the **not-null assertion operator** `!!`. 672 | 673 | Be cautious with this operator. If the object turns out to be `null`, it will result in a `NullPointerException`. 674 | 675 | ```kotlin 676 | val l: Int = name!!.length // Throws NPE if name is null 677 | ``` 678 | 679 | #### Safe Casts (as & as?) 680 | 681 | - For type checks, Kotlin offers both the straightforward `is` operator and the **safe cast** `as?`. This safely casts an object to a type, returning `null` if the cast fails. 682 | 683 | ```kotlin 684 | val cat: Cat? = animal as? Cat // null if animal isn't Cat 685 | ``` 686 | 687 | ### The Elvis Operator: ?: 688 | 689 | The Elvis operator prompts Kotlin to return a non-null value or a **default** or **alternative** value if the operating object is null. 690 | 691 | - It's presented as a double dot `?:`. 692 | - The value on the left of the `?:` will be returned if it's not `null`. Otherwise, the value on the right will be the result: 693 | 694 | ```kotlin 695 | val length: Int = name?.length ?: -1 // If name is null, length is -1 696 | ``` 697 | 698 | Replace **null** values with appropriate defaults, simplifying code and handling absence scenarios. 699 |
700 | 701 | ## 14. What is a โ€œsmart castโ€ in _Kotlin_? 702 | 703 | In Kotlin, a **smart cast** refers to the compiler's ability to automatically cast a variable under certain conditions. This feature significantly reduces code verbosity and casting overhead, ensuring code safety. 704 | 705 | ### How It Works 706 | 707 | The smart cast is automatically applied after the compiler identifies a segment of code where a certain type check has been completed. 708 | 709 | For example, consider the following code snippet: 710 | 711 | ```kotlin 712 | fun processStringOrInt(obj: Any) { 713 | if (obj is String) { 714 | // here, `obj` is smart-cast to a `String` 715 | println(obj.length) 716 | } else if (obj is Int) { 717 | // here, `obj` is smart-cast to an `Int` 718 | println(obj - 1) 719 | } 720 | } 721 | ``` 722 | 723 | ### Code Analysis 724 | 725 | - Within the `if` and `else if` blocks, **smart casts** are triggered. After these checks, the compiler automatically adjusts the type of `obj` for that code block. 726 | - This mechanism eliminates the need for developers to manually cast `obj` within each conditional branch. 727 | 728 | ### Considerations & Limitations 729 | 730 | - **Complexity**: While simple checks like type and `null` are direct matches, more complex contexts, such as generics, may not trigger smart casts in Kotlin. 731 | - **Return Type Ambiguity**: In functions using smart casts, the return type can become ambiguous. If one branch of the condition returns a particular type, the compiler may not know for certain that the other branch never returns that type. This ambiguity can lead to compile-time errors. 732 | - **Capture Scope**: Avoid modifying variables within the smart-cast-conditional blocks. Such modifications can disrupt the typing and lead to unexpected behaviors. 733 | 734 | ### Key Advantages 735 | 736 | - **Code Conciseness**: Smart casts reduce the need for explicit type checks and casts, leading to cleaner and more readable code. 737 | - **Error Prevention**: Smart casts help in avoiding potential errors related to type mismatches and nullability. Once a type is checked, the variable is guaranteed to be of that type within the corresponding code block. 738 |
739 | 740 | ## 15. How do you implement a custom _getter_ and _setter_ in _Kotlin_? 741 | 742 | In Kotlin, you can **customize** property behaviors, including defining your own **custom getters** and **setters**. 743 | 744 | ### Syntax 745 | 746 | Here is the syntax: 747 | 748 | ```kotlin 749 | var [: ] [= ] 750 | get() = 751 | set(value) { } 752 | ``` 753 | 754 | ### Example: Custom Getters/Setters for a `Temperature` Class 755 | 756 | Let's take a look at the code: 757 | 758 | #### Data Model - Temperature.kt 759 | 760 | Here is the Kotlin code: 761 | 762 | ```kotlin 763 | class Temperature { 764 | var celsius: Float = 0f 765 | get() { 766 | return (field * 9 / 5) + 32 767 | } 768 | set(value) { 769 | field = (value - 32) * 5 / 9 770 | } 771 | val fahrenheit: Float 772 | get() = celsius 773 | } 774 | ``` 775 | 776 | #### Activity 777 | 778 | Here is Java code: 779 | 780 | ```java 781 | public class Main { 782 | public static void main(String[] args) { 783 | Temperature weather = new Temperature(); 784 | weather.setCelsius(20); 785 | System.out.println("Temperature in Fahrenheit: " + weather.getFahrenheit()); 786 | } 787 | } 788 | ``` 789 |
790 | 791 | 792 | 793 | #### Explore all 100 answers here ๐Ÿ‘‰ [Devinterview.io - Kotlin](https://devinterview.io/questions/web-and-mobile-development/kotlin-interview-questions) 794 | 795 |
796 | 797 | 798 | web-and-mobile-development 799 | 800 |

801 | 802 | --------------------------------------------------------------------------------