> For the complete documentation index, see [llms.txt](https://amartyushov.gitbook.io/tech/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://amartyushov.gitbook.io/tech/programming-languages/kotlin/effective-kotlin.md).

# Effective Kotlin

## Limiting mutability

1. Immutability makes it easier to parallelize the program
2. References to immutable objects can be cached as they not going to change

### Read-inly properties

```kotlin
class BlaBla {
    val oneTime = calculate() // once during class instantiation calculate() is executed
    val eachTime: Int
        get() = calculate() // !!each time calculate() executes for eachTime access

    val name: String? = "Alex"
    val secondName: String = "Mart"

    val fullName: String?
        get() = name?.let {"$it $secondName"}

    val fullName2 = name?.let {"$it $secondName"}

    fun calculate(): Int {
        println("Calculating...")
        return 42
    }
}

fun main() {
    val instance = BlaBla()

    if (instance.fullName != null) {
        println(instance.fullName?.length) // smartcast doesn't work here as
    }                                      // fullName has custom getter
        // it means compiler still assumes instance.fullName can be null 

    if (instance.fullName2 != null) { // smartcast works here
        println(instance.fullName2.length)
    }
}
```

### Mutable and read-only collections

<figure><img src="/files/GoK3fSqUXtN0EQ8Tnkku" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Down-casting read-only collections to mutable should never take place&#x20;
{% endhint %}

Instead do this

```kotlin
val list = listOf(1,2,3)
val mutableList = list.toMutableList()
mutableList.add(4)
```

### Copy in data classes

```kotlin
class User(
    val name: String,
    val surname: String
) {
    fun withSurname(surname: String) = User(name, surname) // each time new object is cretaed
// but this is immutale, which is good
// on the other hand it is too much to create such function for each class field    
}
```

```kotlin
data class User(
    val name: String,
    val surname: String
)
var user = User("Alex", "Mart")
user = user.copy(surname = "other")

// copy function which comes out of the box for data classes is recommended way to
// keep objects immutable, instead of making fields var
```


---

# 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, and the optional `goal` query parameter:

```
GET https://amartyushov.gitbook.io/tech/programming-languages/kotlin/effective-kotlin.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
