Scope functions apply/with/run/also/let: Where do the names come from?

前端 未结 3 903
梦毁少年i
梦毁少年i 2021-02-01 07:55

There are quite a few blog posts (like this) on usages of the standard library functions apply/with/run/also/let

3条回答
  •  野性不改
    2021-02-01 08:09

    Adding to the @kirillRakhman answer:

    A major part in the naming process was (still is) fluent reading experience in major use cases.

    with:

    with(database) {
        open()
        send()
        close()
    }
    

    apply:

    val v = View().apply {
        width = 3.0
        height = 4.0
        register(this)
    }
    

    also:

    db.users()
        .filter { it.age > 18 }
        .map { account }
        .also { log(it) }
    

    IMHO it doesn't really work with let well. After all, it was taken from "those scary FP languages". But I often think of it as a sort of Let's do this! construct. Like below you could read the code as let's print it!:

    account.map { it.owner }.sumBy {age}.let { print(it) }
    

提交回复
热议问题