{"id":22814313,"url":"https://github.com/devinterview-io/kotlin-interview-questions","last_synced_at":"2025-04-22T18:38:44.327Z","repository":{"id":108757887,"uuid":"326926158","full_name":"Devinterview-io/kotlin-interview-questions","owner":"Devinterview-io","description":"🟣 Kotlin Interview Questions Answered to help you get ready for your next tech interview.","archived":false,"fork":false,"pushed_at":"2024-01-07T17:57:53.000Z","size":33,"stargazers_count":15,"open_issues_count":0,"forks_count":6,"subscribers_count":1,"default_branch":"main","last_synced_at":"2024-01-07T18:50:23.570Z","etag":null,"topics":["kotlin","kotlin-android","kotlin-interview","kotlin-interview-questions"],"latest_commit_sha":null,"homepage":"https://devinterview.io/","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Devinterview-io.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2021-01-05T07:52:24.000Z","updated_at":"2024-01-07T17:57:57.000Z","dependencies_parsed_at":"2023-06-04T17:30:39.853Z","dependency_job_id":null,"html_url":"https://github.com/Devinterview-io/kotlin-interview-questions","commit_stats":null,"previous_names":[],"tags_count":0,"template":null,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fkotlin-interview-questions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fkotlin-interview-questions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fkotlin-interview-questions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fkotlin-interview-questions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Devinterview-io","download_url":"https://codeload.github.com/Devinterview-io/kotlin-interview-questions/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":229388367,"owners_count":18065252,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["kotlin","kotlin-android","kotlin-interview","kotlin-interview-questions"],"created_at":"2024-12-12T13:08:04.305Z","updated_at":"2024-12-12T13:08:04.905Z","avatar_url":"https://github.com/Devinterview-io.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# 100 Important Kotlin Interview Questions\n\n\u003cdiv\u003e\n\u003cp align=\"center\"\u003e\n\u003ca href=\"https://devinterview.io/questions/web-and-mobile-development/\"\u003e\n\u003cimg src=\"https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/github-blog-img%2Fweb-and-mobile-development-github-img.jpg?alt=media\u0026token=1b5eeecc-c9fb-49f5-9e03-50cf2e309555\" alt=\"web-and-mobile-development\" width=\"100%\"\u003e\n\u003c/a\u003e\n\u003c/p\u003e\n\n#### You can also find all 100 answers here 👉 [Devinterview.io - Kotlin](https://devinterview.io/questions/web-and-mobile-development/kotlin-interview-questions)\n\n\u003cbr\u003e\n\n## 1. What is _Kotlin_ and how does it interoperate with _Java_?\n\n**Kotlin** is a modern, statically typed language. Having been developed by JetBrains, it targets the JVM, among other platforms.\n\n### Key Strengths of Kotlin on JVM\n\n- **Concise Syntax**: Kotlin's compact code minimizes boilerplate.\n- **Null Safety**: With its nullable types, Kotlin helps reduce null-pointer exceptions.\n- **Extension Functions**: These functions simplify class extension.\n- **Coroutines**: Kotlin's lightweight threads make asynchronous operations more manageable.\n- **Immutability**: Kotlin has built-in support for immutable structures through 'val'.\n\n### Core Java-Kotlin Interoperability Mechanisms\n\n**Kotlin** can use Java Frameworks and libraries. Plus, it offers mechanisms for both Java-to-Kotlin and Kotlin-to-Java interoperability.\n\nThese mechanisms include:\n\n1. **Kotlin Libraries and Frameworks**: They are tested to work with Java.\n2. **nullability Roadmap and @Nullable/@NotNull Annotations**: One can take advantage of both Kotlin's null-safe types and Java's nullability guidelines.\n3. **Supportive Native Tools**: Kotlin paves the way for Android development with libraries compatible with Java.\n4. **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.\n\n### Common Scenarios for Java-Kotlin Interoperability\n\n- **Migrating Codebases**: Gradual transitions are possible. Both languages can interoperate within a single project.\n  \n- **Collaborative Development**: Team members who prefer different languages can still contribute to the common codebase.\n\n- **Libraries and Frameworks**: Leveraging Java libraries in a Kotlin-based system is seamless.\n\n- **Android Development**: Kotlin has been officially backed by Google as a primary language for Android app development.\n\n- **VM and Platform Independence**: Kotlin's multi-platform capabilities allow functionality sharing across different platforms.\n\n### Java-Kotlin Code Example: Interoperability\n\nHere is the Java class:\n\n```java\npublic class Fruit {\n    private String name;\n    private int quantity;\n\n    public Fruit(String name, int quantity) {\n        this.name = name;\n        this.quantity = quantity;\n    }\n\n    public String getName() {\n        return name;\n    }\n\n    public int getQuantity() {\n        return quantity;\n    }\n\n    public void setName(String name) {\n        this.name = name;\n    }\n\n    public void setQuantity(int quantity) {\n        this.quantity = quantity;\n    }\n}\n```\n\nAnd here is the Kotlin class that uses the `Fruit` Java class:\n\n```kotlin\nfun main() {\n    val apple = Fruit(\"Apple\", 10)  // Use of Java class\n    println(\"Name: ${apple.name}, Quantity: ${apple.quantity}\")\n\n    apple.name = \"Green Apple\"      // Kotlin syntax for modifying Java object\n    apple.quantity += 5\n\n    println(\"Updated Apple: Name - ${apple.name}, Quantity - ${apple.quantity}\")\n}\n```\n\u003cbr\u003e\n\n## 2. How does _Kotlin_ improve upon _Java_ for _Android development_?\n\n**Kotlin**, a statically-typed language, provides several benefits over Java in the context of Android development.\n\n### Improved Developer Experience\n\n- **Intuitive Syntax**: Kotlin reduces boilerplate code, leading to more elegant, succinct, and readable codebases.\n- **Extension Functions**: This language feature allows developers to extend specific types with new functionalities.\n\n### Enhanced Productivity\n\n- **Null Safety**: The type system in Kotlin differentiates between nullable and non-nullable references, effectively reducing `NullPointerException` occurrences.\n- **Smart Casting**: The language's type inference allows automatic casting of types wherever possible, thereby eliminating the need for explicit casting.\n- **Coroutines**: Kotlin's built-in support for coroutines makes asynchronous programming simpler and less error-prone.\n\n### Modern Language Features\n\n- **Lambdas**: Kotlin's support for concise yet powerful lambda expressions outstrips that of Java.\n- **Data Classes**: These classes, which Kotlin can generate getters, setters, `equals()`, and other basic methods automatically make working with models more streamlined.\n- **Type Inference**: The language can often discern the type of a variable from its value, thus alleviating the need for explicit type declarations.\n\n### Compatibility with Java\n\n- **Interoperability with Java**: Kotlin integrates seamlessly with existing Java code, allowing for easy migration and coexistence.\n- **Full Java SDK Support**: Kotlin is fully compatible with the Java SDK, enabling access to the plethora of Java libraries from Kotlin projects.\n\n### Enhanced Safety and Accuracy\n\n- **Immutability by Default**: In Kotlin, variables are, by default, immutable (read-only). This approach is conducive to preventing bugs and improving code safety.\n- **Parameterized Contracts**: The `where` clause in Kotlin ensures more robust compile-time checks for generic types.\n- **Range and Step Constructs**: These features enhance data accuracy and prevent out-of-bounds access.\n\u003cbr\u003e\n\n## 3. What are the basic types in _Kotlin_?\n\n**Kotlin** has a rich set of built-in data types tailored for various uses. They are mostly categorized into **Primitive** and **Object** data types.\n\n### Basic Types Categories\n\n#### **Primitive Types**\n\n**Kotlin** introduces the following **Primitive** types:\n- `Double`: Double precision 64-bit floating point number.\n- `Float`: Single precision 32-bit floating point number.\n- `Long`: 64-bit integer.\n- `Int`: 32-bit integer.\n- `Short`: 16-bit integer.\n- `Byte`: 8-bit integer.\n- `Char`: A single 16-bit Unicode character.\n- `Boolean`: Represents truth values: true or false.\n\n#### **Object Types**\n\nThese are **Object** types:\n\n- `String`: A sequence of characters.\n- `Any`: The root of the Kotlin class hierarchy. This is the equivalent of `Object` in Java.\n\n#### Other Types\n\n- `Array`: A class for array types.\n- `Function`: A function type, which is determined by its parameter types and return type.\n\nYou can have a look at the Kotlin code.\n\nHere is the Kotlin code:\n\n### Code Example: Kotlin Types\n\n```kotlin\nfun main() {\n    val doubleNum: Double = 100.0\n    val floatNum: Float = 100.0f\n    val longNum: Long = 100\n    val intNum: Int = 100\n    val shortNum: Short = 100\n    val byteNum: Byte = 100\n    val charLetter: Char = 'A'\n    val isRainingToday: Boolean = true\n    val text: String = \"Hello, Kotlin!\"\n\n    val anyValue: Any = \"This is an example of Any type in Kotlin\"\n\n    val intArray: Array\u003cInt\u003e = arrayOf(1, 2, 3, 4, 5)\n    val strArray: Array\u003cString\u003e = Array(5) { \"Item #$it\" }\n\n    fun myFunction(num: Int): Boolean {\n        return num % 2 == 0\n    }\n\n    val myFunctionType: (Int) -\u003e Boolean = ::myFunction\n}\n```\n\u003cbr\u003e\n\n## 4. Explain the difference between `val` and `var` in _Kotlin_.\n\nIn Kotlin, the keywords `val` and `var` are used for **variable declaration**, each with distinct mutability characteristics.\n\n### Immutable with `val`\n\n`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.\n\n### Mutable with `var`\n\n`var` designates a **mutable reference**. This type of variable allows both reassignment and potential state changes during its lifecycle.\n\n### Tips for Usage\n\n- **Prefer `val`**: Use it unless there's a compelling reason for mutability. This practice aligns with Kotlin's design for immutability.\n  \n- **Mutable Limited**: In production code, restrict mutability with `var` to situations where its necessity is clear and justified.\n\n### Code Example: `val` and `var`\n\nHere is the Kotlin code:\n\n```kotlin\nfun main() {\n    val PI = 3.14159  // Immutable PI, defined with val\n    var count = 0     // Mutable count, defined with var\n  \n    // Following lines lead to compiler errors\n    PI = 3.14       // Cannot reassign PI as it's declared with val, not var\n    count = 1       // OK! Reassignment of a variable defined with var is allowed\n}\n```\n\u003cbr\u003e\n\n## 5. How do you create a _singleton_ in _Kotlin_?\n\nIn Kotlin, defining a **singleton** is straightfoward; the language provides a dedicated `object` keyword.\n\nWhen you declare a companion object in a class, it becomes a singleton accessible through the class name. This is useful for creating global handles.\n\n### Singleton Using `object` Keyword\n\n- **Kotlin Code**:  \n\n```kotlin\nobject MySingleton {\n    fun someFunction() {\n        // Logic here\n    }\n}\n```\n\n- **Access**:\n\n  ```kotlin\n  MySingleton.someFunction()\n  ```\n\n### Singleton through `Companion Object`\n\n- **Kotlin Code:**  \n\n  ```kotlin\n  class MySingletonClass {\n      companion object {\n          fun someFunction() {\n              // Logic here\n          }\n      }\n  }\n  ```\n\n- **Access**:\n\n  ```kotlin\n  MySingletonClass.someFunction()\n  ```\n\n### Why Use `object` over `companion object`?\n\nIf a class doesn't require an instance or has a single instance throughout the application, `object` is the most succinct and expressive solution.\n\nIn 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.\n\n### `object` Versus Traditional Singletons\n\nKotlin'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.\n\nTraditional Java singletons also had complications with lazy initialization and thread safety, which are non-issues with Kotlin's `object`.\n\nFrom a design standpoint, the single-responsibility principle should guide the decision to use singletons. Cohesiveness allows for consistency and predictability across the app.\n\n### Key Takeaways:\n\n- Kotlin's `object` keyword is the most straightforward way to create singletons.\n- `companion object` is appropriate for singletons tied to the containing class where both need to be instantiated.\n- Kotlin's `object` is a modern, expressive alternative to the verbosity and potential issues of traditional Java singletons.\n- Threading and resource management are handled seamlessly, simplifying code.\n\u003cbr\u003e\n\n## 6. What are the _Kotlin type inference_ rules?\n\nKotlin **type inference** represents a powerful feature that automatically determines variable types. Nonetheless, it does so within the constraints of **Kotlin's Type Hierarchy**.\n\n- Kotlin types are static, meaning they're determined at compile time.\n- The Kotlin compiler analyses assignments and method calls to infer types.\n- 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.\n\nKotlin also supports **type inference** with:\n\n- **Lambda expressions**\n- **Generics**\n\nThe 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.\n\n### Type Inference With Lambdas\n\nIn 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.\n\nThe `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`.\n\n#### Code Example: Type Inference With Lambdas\n\nHere is the Kotlin code:\n\n```kotlin\nfun main() {\n    val names = listOf(\"Alice\", \"Bob\")\n\n    // Infers `it` as String\n    val lengths: List\u003cInt\u003e = names.map { it.length }\n\n    println(lengths)  // Output: [5, 3]\n}\n```\n\u003cbr\u003e\n\n## 7. Can _Kotlin code_ be executed without a `main` function?\n\nWhile 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.\n\n### Direct Execution in Kotlin\n\nThe directive to execute code without a `main` function is termed **script mode** and is enabled using the following steps:\n\n1. Define a build and execution environment through the Kotlin compiler or the IntelliJ IDEA.\n2. Ensure that the script file has **.kts** or **kotlin-script** extension to indicate it's a Kotlin script.\n\nThis 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.\n\u003cbr\u003e\n\n## 8. What is the purpose of the `Unit` type in _Kotlin_?\n\nWhile some languages use \"void\" to indicate functions or expressions with no useful return value, **Kotlin** leverages the Unit type.\n\n### Why Kotlin Introduced 'Unit'\n\nThe driving principle behind introducing the `Unit` type was to provide a unified approach to functions across the **object-oriented** and **functional** programming paradigms.\n\n### Key Characteristics of `Unit`\n\n- **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.\n- **Immutable State**: As a singleton, `Unit` is inherently immutable, ensuring that every function call returning `Unit` produces the same fixed value.\n\n### Use Cases\n\n1. **Functionality Communication**: `Unit` serves as a clear signal that a function is invoked strictly for its side effects.\n2. **Interface Alignment**: Codebases aiming for consistency can utilize `Unit` to harmonize function return types.\n\n### Code Example: Unit in Functions\n\nHere is the Kotlin code:\n\n```kotlin\n// Function with explicit Unit return type\nfun greet(name: String): Unit {\n    println(\"Hello, $name!\")\n}\n\n// Function without explicit return type defaults to Unit\nfun performTask(): Unit {\n    // Task logic goes here\n}\n\n// Function with no explicit return type\nfun noReturn(): Nothing? {\n    // Code that will never execute\n    throw NotImplementedError()\n}\n\nfun main() {\n    // All three function calls here can be understood as returning Unit\n    greet(\"Alice\")\n    performTask()\n    println(noReturn()) // Will not print anything\n}\n```\n\nIn 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.\n\u003cbr\u003e\n\n## 9. How do you perform _string interpolation_ in _Kotlin_?\n\nIn Kotlin, you can **interpolate** strings using the `$` symbol. This mechanism allows for the direct embedding of variables, expressions, and Math operations within a string.\n\nAlternatively, you can leverage **raw strings** with the `trimMargin` method for multi-line text.\n\n### Code Example: String Interpolation\n\nHere is the Kotlin code:\n\n```kotlin\nfun main() {\n    val name = \"Alice\"\n    val age = 25\n\n    println(\"Name: $name, Age: $age\")\n    \n    // Dollar sign within a string\n    println(\"$$100: A Hundred Dollars\")\n    \n    // Interpolated expression\n    val tripleAge = age * 3\n    println(\"In 3 years, $name will be ${age + 3} years old, and 3 times $age is $tripleAge\")\n\n    // Raw string with trimMargin\n    val poem = \"\"\"\n        |Two roads diverged in a yellow wood,\n        |And sorry I could not travel both\n        |And be one traveler\n        \"\"\".trimMargin()\n    println(poem)\n}\n```\n\n### Output\n\n```\nName: Alice, Age: 25\n$100: A Hundred Dollars\nIn 3 years, Alice will be 28 years old, and 3 times 25 is 75\nTwo roads diverged in a yellow wood,\nAnd sorry I could not travel both\nAnd be one traveler\n```\n\u003cbr\u003e\n\n## 10. What are _extension functions_ in _Kotlin_?\n\n**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.\n\n### Benefits of Extension Functions\n\n- **Improved Readability**: Extension functions enable adding context-specific methods to types.\n  \n- **Consistent Naming**: These functions ensure a standard naming convention for classes.\n\n- **No Inheritance Issues**: Overriding is not a concern, making extension functions ideal for providing custom behavior to existing classes.\n  \n- **Modular Code**: Associates utility methods directly with the classes they operate on, streamlining code organization.\n\n### Function vs. Method\n\nIn Kotlin, the term **\"function\"** typically refers to a top-level function, whereas the term **\"method\"** is used within the context of a class.\n\n### Usage\n\n1. **Importing Extension Functions**: Kotlin's standard library provides numerous extension functions. Additional extensions can be imported using the `import` directive.\n\n2. **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.\n\n3. **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.\n\n4. **Inheritance**: When a class and its parent provide methods of the same name and signature, the class's own methods always take precedence.\n\n   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.\n\n### Code: Extension Function on Nullable Type\n\nHere is the Kotlin code:\n\n```kotlin\nfun String?.isNullEmptyOrBlank(): Boolean {\n    return this == null || this.isEmpty() || this.isBlank()\n}\n\nfun main() {\n    val text: String? = \"Hello\"\n    val emptyText: String? = \"\"\n    val blankText: String? = \"   \"\n\n    println(text.isNullEmptyOrBlank())  // false\n    println(emptyText.isNullEmptyOrBlank())  // true\n    println(blankText.isNullEmptyOrBlank())  // true\n}\n```\nIn 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.\n\u003cbr\u003e\n\n## 11. How are `if` expressions used in _Kotlin_ as compared to _Java_?\n\nWhile both Kotlin and Java use `if` **expressions** to conditionally execute code, Kotlin offers more power and flexibility with its `if` expression.\n\n### Key Differences\n\n- **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.\n  \n- **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.\n\n- **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.\n\n#### Example: If-Else Expression\n\nHere is the Kotlin code:\n\n```kotlin\nval result = if (condition) \"Value1\" else \"Value2\"\n```\n\nAnd here is the equivalent Java code:\n\n```java\nString result;\nif (condition) {\n    result = \"Value1\";\n} else {\n    result = \"Value2\";\n}\n```\n\n### Best Practices\n\n- **Kotlin Compactness**: Utilize Kotlin's concise syntax for improved readability and maintainability.\n  \n- **Type Inference**: In Kotlin, you may let the compiler infer the result type rather than explicitly defining it.\n\u003cbr\u003e\n\n## 12. Explain `when` expressions in _Kotlin_.\n\nIn **Kotlin**, the `when` expression is a powerful control-flow construct that simplifies and enhances many operations.\n\nIt 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.\n\n### Key Features\n\n- **Branching**: Similar to `switch` statements, `when` evaluates different conditions and triggers corresponding code blocks.\n- **Expression-based**: It works well in both code blocks and as standalone expressions.\n- **Versatile Syntax**: It supports a broad range of matching techniques, such as value matching, range checks, and null safety operators.\n- **Extensive Filtering**: Can evaluate conditions like type checks, boolean expressions, and custom checks.\n- **Sealed Classes Support**: Seamlessly integrates with sealed classes, enforcing a comprehensive check of all possible subtypes.\n\n### Code Example: Basic when-expression\n\nHere is the Kotlin code:\n\n```kotlin\nfun describe(object: Any): String {\n    return when (object) {\n        1 -\u003e \"One\"\n        2 -\u003e \"Two\"\n        3, 4 -\u003e \"Three or Four\"\n        is String -\u003e \"That's a string\"\n        is Number -\u003e \"That's a number\"\n        else -\u003e \"Something else\"\n    }\n}\n\nfun main() {\n    println(describe(1))\n    println(describe(3))\n    println(describe(5))\n    println(describe(\"hello\"))\n}\n```\n\nWhen you run the above code, you will get the following output:\n\n```plaintext\nOne\nThree or Four\nSomething else\nThat's a string\n```\n\n### Code Example: Returning Booleans\n\nHere is the Kotlin code:\n\n```kotlin\nfun isStringOrEmpty(input: Any?): Boolean {\n    return when (input) {\n        null -\u003e true\n        is String -\u003e input.isEmpty()\n        else -\u003e false\n    }\n}\n\nfun main() {\n    println(isStringOrEmpty(null))\n    println(isStringOrEmpty(\"\"))\n    println(isStringOrEmpty(123))\n}\n```\n\nWhen you run the above code, you will get the following output:\n\n```plaintext\ntrue\ntrue\nfalse\n```\n\n### Advanced Example: Data Classes and Smart Casting\n\nHere is the Kotlin code:\n\n```kotlin\ndata class Person(val name: String, val age: Int, val email: String = \"\")\n\nfun processPerson(person: Person) {\n    when {\n        person.age \u003c 0 -\u003e println(\"Invalid age!\")\n        person.name.isBlank() -\u003e println(\"No name provided\")\n        person.email.isBlank() -\u003e println(\"No email provided\")\n        else -\u003e {\n            println(\"All details provided:\")\n            println(\"Name: ${person.name}\")\n            println(\"Age: ${person.age}\")\n            println(\"Email: ${person.email}\")\n        }\n    }\n}\n\nfun main() {\n    val person1 = Person(\"Alice\", 25, \"alice@example.com\")\n\n    val person2 = Person(\"Bob\", 30)\n  \n    val person3 = Person(\"\", -10, \"invalidemail\")\n\n    processPerson(person1) // Should print all details\n    processPerson(person2) // Should print \"No email provided\"\n    processPerson(person3) // Should print \"Invalid age!\"\n}\n```\n\n- We define a data class, `Person`.\n- 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`.\"\n\u003cbr\u003e\n\n## 13. How does _Kotlin_ handle _null safety_ and what is the _Elvis operator_?\n\nIn 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.\n\nThe **Elvis Operator** provides a concise means for handling `null` values within expressions.\n\n### Null Safety\n\nKotlin employs a set of rules to manage nullability in objects:\n\n#### Nullable Types\n\n- A type is marked as **nullable** if it can accept `null` values. This is indicated by appending `?` to the type name.\n\n  ```kotlin\n  val name: String? = null  // Nullable String\n  ```\n\n- 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.\n\n#### Safe Calls\n\n- 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`:\n\n  ```kotlin\n  val length: Int? = name?.length  // null if name is null\n  ```\n\n#### The Not-Null Assertion Operator\n\n- When you're certain an object isn't `null`, you can use the **not-null assertion operator** `!!`.\n\n  Be cautious with this operator. If the object turns out to be `null`, it will result in a `NullPointerException`.\n\n  ```kotlin\n  val l: Int = name!!.length  // Throws NPE if name is null\n  ```\n\n#### Safe Casts (as \u0026 as?)\n\n- 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.\n\n  ```kotlin\n  val cat: Cat? = animal as? Cat  // null if animal isn't Cat\n  ```\n\n### The Elvis Operator: ?: \n\nThe Elvis operator prompts Kotlin to return a non-null value or a **default** or **alternative** value if the operating object is null.\n\n- It's presented as a double dot `?:`.\n- 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:\n\n  ```kotlin\n  val length: Int = name?.length ?: -1  // If name is null, length is -1\n  ```\n\nReplace **null** values with appropriate defaults, simplifying code and handling absence scenarios.\n\u003cbr\u003e\n\n## 14. What is a “smart cast” in _Kotlin_?\n\nIn 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.\n\n### How It Works\n\nThe smart cast is automatically applied after the compiler identifies a segment of code where a certain type check has been completed.\n\nFor example, consider the following code snippet:\n\n```kotlin\nfun processStringOrInt(obj: Any) {\n    if (obj is String) {\n        // here, `obj` is smart-cast to a `String`\n        println(obj.length)\n    } else if (obj is Int) {\n        // here, `obj` is smart-cast to an `Int`\n        println(obj - 1)\n    }\n}\n```\n\n### Code Analysis\n\n- 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.\n- This mechanism eliminates the need for developers to manually cast `obj` within each conditional branch.\n\n### Considerations \u0026 Limitations\n\n- **Complexity**: While simple checks like type and `null` are direct matches, more complex contexts, such as generics, may not trigger smart casts in Kotlin.\n- **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.\n- **Capture Scope**: Avoid modifying variables within the smart-cast-conditional blocks. Such modifications can disrupt the typing and lead to unexpected behaviors.\n\n### Key Advantages\n\n- **Code Conciseness**: Smart casts reduce the need for explicit type checks and casts, leading to cleaner and more readable code.\n- **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.\n\u003cbr\u003e\n\n## 15. How do you implement a custom _getter_ and _setter_ in _Kotlin_?\n\nIn Kotlin, you can **customize** property behaviors, including defining your own **custom getters** and **setters**.\n\n### Syntax\n\nHere is the syntax:\n\n```kotlin\nvar \u003cpropertyName\u003e[: \u003cPropertyType\u003e] [= \u003cproperty_initializer\u003e]\n    get() = \u003ccustom_getter\u003e\n    set(value) { \u003ccustom_setter\u003e }\n```\n\n### Example: Custom Getters/Setters for a `Temperature` Class\n\nLet's take a look at the code:\n\n#### Data Model - Temperature.kt\n\nHere is the Kotlin code:\n\n```kotlin\nclass Temperature {\n    var celsius: Float = 0f\n        get() {\n            return (field * 9 / 5) + 32\n        }\n        set(value) {\n            field = (value - 32) * 5 / 9\n        }\n    val fahrenheit: Float\n        get() = celsius\n}\n```\n\n#### Activity\n\nHere is Java code:\n\n```java\npublic class Main {\n    public static void main(String[] args) {\n        Temperature weather = new Temperature();\n        weather.setCelsius(20);\n        System.out.println(\"Temperature in Fahrenheit: \" + weather.getFahrenheit());\n    }\n}\n```\n\u003cbr\u003e\n\n\n\n#### Explore all 100 answers here 👉 [Devinterview.io - Kotlin](https://devinterview.io/questions/web-and-mobile-development/kotlin-interview-questions)\n\n\u003cbr\u003e\n\n\u003ca href=\"https://devinterview.io/questions/web-and-mobile-development/\"\u003e\n\u003cimg src=\"https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/github-blog-img%2Fweb-and-mobile-development-github-img.jpg?alt=media\u0026token=1b5eeecc-c9fb-49f5-9e03-50cf2e309555\" alt=\"web-and-mobile-development\" width=\"100%\"\u003e\n\u003c/a\u003e\n\u003c/p\u003e\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevinterview-io%2Fkotlin-interview-questions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdevinterview-io%2Fkotlin-interview-questions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevinterview-io%2Fkotlin-interview-questions/lists"}