> For the complete documentation index, see [llms.txt](https://androidbytesensei.gitbook.io/interview-preparation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://androidbytesensei.gitbook.io/interview-preparation/interview-questions/android-kotlin-notes-level-2.md).

# Android Kotlin — Notes Level 2

<figure><img src="https://miro.medium.com/v2/resize:fit:720/format:webp/0*8XxyCBceCOR6GNYo" alt=""><figcaption></figcaption></figure>

Here’s the some questions and answers which are asking by interviewers , we may also use as notes

### **1. What’s a const? How does it differ from a val?**

* By default val properties are set at runtime. Adding a const modifier on a val would make a compile-time constant.
* A const cannot be used with a var or on its own.
* A const is not applicable on a local variable.

### 2. **How is “ !! ” different from “ ?. ” in unwrapping the nullable values? Is there any other way to unwrap nullable values safely?**

* !! i**s used to force unwrap** the nullable type to get the value. If the value returned is a null, it would lead to a runtime crash. Hence a !! operator should be only used when **you’re absolutely sure that the value won’t be null** at all.

```
val name: String? = "John"
val length = name!!.length  // Returns length of "John"

val nullName: String? = null
val nullLength = nullName!!.length  // Throws NullPointerException
```

* Otherwise, you’ll get the dreaded null pointer exception. On the other hand, a **?.** is an Elvis Operator that does a safe call.
* We can use the lambda expression let on the nullable value to unwrap safely.

```
val name: String? = "John"
val length = name?.length  // Returns 4

val nullName: String? = null
val nullLength = nullName?.length  // Returns null, no exception
```

```
val name: String? = "John"
name?.let {
    println("Name is not null: $it")  // Executes only if name is not null
}
```

### 3. Does the following inheritance structure compile?

```
class A{ }
class B : A(){ }
```

* **NO**. By default classes are final in Kotlin.
* To make them non-final, you need to add the open modifier.

### 4. Types of constructors in Kotlin? How are they different? How do you define them in your class?

Constructors in Kotlin are of two types:

* **Primary** — These are defined in the class headers. They cannot hold any logic. There’s only one primary constructor per class.
* **Secondary** — They’re defined in the class body. They must delegate to the primary constructor if it exists. They can hold logic. There can be more than one secondary constructor.

### 5. **init block in Kotlin**

* init is the initialiser block in Kotlin. It’s executed once the primary constructor is instantiated. If you invoke a secondary constructor, then it works after the primary one as it is composed in the chain.

### 6. **What’s the type of arguments inside a constructor?**

* By default, the constructor arguments are val unless explicitly set to var.

### 7. **What are data classes in Kotlin? What makes them so useful? How are they defined?**

* A data class is essentially a concise way to define a class whose primary purpose is to store data, with additional functionality (like equality checks, string representations, and copy operations) automatically generated by the Kotlin compiler.

When you declare a class as a **data class**, Kotlin automatically provides the following methods for you:

* **`toString()`**: A string representation of the data class is generated, which includes the class name and its properties. This makes it easy to print the object for debugging or logging purposes.
* **`equals()`**: This method checks if two data class instances are equal based on their property values (not by reference). This is often used in collections where object equality needs to be checked.
* **`hashCode()`**: Generates a hash code for the data class, which is useful for hashing algorithms, such as in `HashMap` or `HashSet`.
* **`copy()`**: This method allows you to create a copy of the object with some properties changed. It’s great for working with immutable data in a functional style.
* **`componentN()`**: For each property in the data class, a `componentN()` function is automatically generated (where `N` is the index of the property). These are used for destructuring declarations, allowing you to unpack the properties of the object easily.

### 8. Note — There is no ternary conditional operator in Kotlin language.

### 9. **Ranges operator in Kotlin?**

* Ranges operator helps to iterate through a range.
* Its operator form is (..)

```
for (i in 1..15)
    print(i)
```

### 10. The Structural Expressions In Kotlin?

**They are:**

* **Return:** It returns from the nearest enclosing function or anonymous function by default.
* **Break:** This expression terminates the closest enclosing loop.
* **Continue:** This expression precedes you to the next closest enclosing loop.

### 11. **How to change the value of the val ?**

* In Kotlin, **`val`** variables themselves are immutable, meaning their reference cannot be changed after initialization. However, if a `val` variable refers to a mutable object (like a mutable collection or a class with mutable properties), you **can modify the internal state of that object** by using functions or methods. The key point is that while the reference to the object is immutable, the **object itself** may still be mutable, and its state can be modified.

```
fun addElementToList(list: MutableList<Int>, element: Int) {
    list.add(element)  // Modifying the list's contents
}

fun main() {
    val numbers = mutableListOf(1, 2, 3)  // `val` variable pointing to a mutable list

    addElementToList(numbers, 4)  // Using a function to modify the list's contents
    println(numbers)  // Output: [1, 2, 3, 4]

    // numbers = mutableListOf(5, 6)  // This would be an error because `numbers` is a `val`
}
```

### 12. **Is** keyword

* Is keyword checking type of object or class

```
val any: Any = "vivek"
if(any is String){
    println(any.length)
}
```

### 13. Type of arguments

```
// Positional
fun getName(myName:String){
    println(myName)
}

// Default argument
fun getName(myName:String,acti:Boolean=false){
    println(myName)
}

// Named Arguments
fun main() {
    getName(age=12,acti=true,myName="Vivek")
}


fun getName(myName:String,acti:Boolean=false,age:Int=2){
    println(myName)
}

// Extension function
fun main() {
    var stu = Student()
    println(stu.hasPassed(40))
    println(stu.hasPassed(97))
}


fun Student.isScholar(marks:Int):Boolean{
    return marks > 95;
}


class Student{
    fun hasPassed(marks:Int):Boolean{
        return marks > 40;
    }
}
```

Help to make this better version , adding more content and helpful notes


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://androidbytesensei.gitbook.io/interview-preparation/interview-questions/android-kotlin-notes-level-2.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
