Sobes.tech
Junior — Middle

What scope functions in Kotlin do you know?

sobes.tech AI

Answer from AI

In Kotlin, scope functions are functions that allow performing operations on an object within a certain context. The main scope functions are:

  • let — executes a block of code with the object as it and returns the result of the block. Often used for safe calls with nullable objects.

    val name: String? = "Kotlin"
    name?.let {
        println("Name length: ${it.length}")
    }
    
  • run — executes a block of code with the object as this and returns the result of the block. Useful for initialization and calculations.

    val result = "Hello".run {
        println(this)
        length
    }
    
  • with — similar to run, but called as a function with the object as a parameter, returning the result of the block.

    val builder = StringBuilder()
    val result = with(builder) {
        append("Hello")
        append(" World")
        toString()
    }
    
  • apply — executes a block with the object as this, returns the object itself. Often used for object configuration.

    val person = Person().apply {
        name = "John"
        age = 30
    }
    
  • also — executes a block with the object as it, returns the object itself. Used for additional actions like logging.

    val numbers = mutableListOf(1, 2, 3).also {
        println("List: $it")
    }
    

Each function differs in how it passes the object to the lambda (this or it) and what it returns (the result of the block or the object itself).