let()

Declaration

/**
 * Calls the specified function [block] with `this` value as its argument and returns its result.
 */
@kotlin.internal.InlineOnly
public inline fun <T, R> T.let(block: (T) -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block(this)
}

let() is a scoping function: use it whenever you want to define a variable for a specific scope of your code but not beyond.

When using this function we have to know about 3 things:

  • receiver (this)
  • argument (it)
  • result
receiver (this) argument (it) result
class MyClass {
  fun test() {
   val str: String = "..."
   val result = str.let {
   print(this) // Receiver
   print(it) // Argument
   42 //Block return value
        }
    }
}
this@MyClass String(“…”) Int(42)

Usage

  • to keep your code nicely self-contained so that you don’t have variables “leaking out”.
ApiHelper.getURL.let {imageView.loadImage(it) }
// url(it) is no longer visible here
  • an alternative to testing against null.
 url.let {imageView.loadImage(it) //only when url is not null }

apply()

Declaration

/**
 * Calls the specified function [block] with `this` value as its receiver and returns `this` value.
 */
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block()
    return this
}

apply() defines an extension function on all types. When you invoke it, it calls the closure passed in parameter and then returns the receiver object that closure ran on.

Usage

with()

Declaration

/**
 * Calls the specified function [block] with the given [receiver] as its receiver and returns its result.
 */
@kotlin.internal.InlineOnly
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return receiver.block()
}

Usage

run()

Declaration

/**
 * Calls the specified function [block] and returns its result.
 */
@kotlin.internal.InlineOnly
public inline fun <R> run(block: () -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block()
}

Usage

The difference between them

function Receiver (this)  Argument (it) Result
class MyClass {
  fun test() {
    val str: String = "..."
    val result= str.xxx{
// Receiver
    print(this)

// Argument
    print(it) 

// Block return value
    42 
        }
    }
}
let

run

run*

with*

apply

also

 

this@MyClass

String(“…”)

this@MyClass

String(“…”)

String(“…”)

this@MyClass

 

String(“…”)

N/A

N/A

N/A

N/A

String(“…”)

Int(42)

Int(42)

Int(42)

Int(42)

String(“…”)

String(“…”)

A nature, universe, science, music, love lover

Leave a Reply

Your email address will not be published. Required fields are marked *

Bitnami