Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
643 views
in Technique[技术] by (71.8m points)

kotlin - What is a purpose of Lambda's with Receiver?

What is a purpose of Lambda's with Receiver in Kotlin, while we have extension functions ?

Two functions below do the same things, however first one is more readable and short:

fun main(args: Array<String>) {
    println("123".represents(123))
    println(123.represents("123"))
}

fun String.represents(another: Int) = toIntOrNull() == another

val represents: Int.(String) -> Boolean = {this == it.toIntOrNull()}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Lambdas with receivers are basically exactly the same as extension functions, they're just able to be stored in properties, and passed around to functions. This question is essentially the same as "What's the purpose of lambdas when we have functions?". The answer is much the same as well - it allows you to quickly create anonymous extension functions anywhere in your code.

There are many good use cases for this (see DSLs in particular), but I'll give one simple example here.

For instance, let's say you have a function like this:

fun buildString(actions: StringBuilder.() -> Unit): String {
    val builder = StringBuilder()
    builder.actions()
    return builder.toString()
}

Calling this function would look like this:

val str = buildString {
    append("Hello")
    append(" ")
    append("world")
}

There are a couple interesting things this language feature enabled:

  • Inside the lambda you pass to buildString, you're in a new scope and as such have new methods and properties available for use. In this specific case, you can use methods on the StringBuilder type without having to call them on any instance.
  • The actual StringBuilder instance these function calls are going to be made on is not managed by you - it's up to the internal implementation of the function to create one and call your extension function on it.
  • Consequently, it would also be possible for this function to do much more than just call the lambda you passed to it once on one StringBuilder - it could call it multiple times, on various StringBuilder instances, store it for later use, etc.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...