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

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

Down-casting read-only collections to mutable should never take place

Instead do this

Copy in data classes

Last updated

Was this helpful?