Kotlin Higher-order functions - kotlin

I am new in function programming language and I just came through a new concept called Higher-order function.
I have seen some of the Higher-order functions such as filter(), map(), flatMap(), take(), drop() and zip(). I only able to get details of this higher-order functions.
My question is: These are the only higher-order functions available in kotlin or there are more higher-order functions also available.
I am not sure, Can we also create higher-order functions for personal use or not?
Thanks in advance.

Yes, there are many more higher-order functions in Kotlin, e.g., apply, also, lazy, let, onSuccess, recover, recoverCatching, repeat, run, runCatching, suspend, with, use. Explore the reference documentation for functions that consume other functions as values, e.g., https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/, https://kotlinlang.org/docs/tutorials/kotlin-for-py/functional-programming.html#nice-utility-functions.
Yes, users can define higher-order functions. Refer to https://kotlinlang.org/docs/reference/lambdas.html for info about how to define and use higher-order functions.

As mentioned in the Comparison to Java page's 4th point, Kotlin has proper function types, as opposed to Java's SAM-conversions.
What I mean by that is if you want to accept a function or some sort of code in Java that you can call inside a function you need an external interface having exactly 1 method which is aware of the return type and the parameter signature.
For example in Java:
// You can't create this unless you create FuncInterface defining its parameter and return type
MyFuncInterface a = (s) -> System.out.println(s);
interface MyFuncInterface {
public void myMethod(String s);
}
// now call a like
a.myMethod("Hello World"); // will print: Hello World
a.myMethod("Test"); // will print: Test
While it is not the case in kotlin, you can create lambda without creating an interface here.
For example same code in Kotlin could be converted into:
val a: (String) -> Unit = { println(it) }
// or like this: val a: (String) -> Unit = { s -> println(s) }
// call like this
a("Hello World") // will print: Hello World
a("Test") // will print: Test
Since Kotlin has proper function types, you can make a function accept a function type or return one, which is then be called a Higher-Order Function.
Concept is similar:
// This is a higher order functon, takes a callable function `f`
fun operatesFOn(num1: Int, num2: Int, f: (Int, Int) -> Int) {
// this types are useful as callbacks, instead of taking nums and passing them
// you can compute heavy tasks and when they complete call f with the result
return f(num1, num2)
}
// lambda can be put outside the parentheses if it is last parameter
// also is another higher order function which calls the lambda passed with the object it was called on as a parameter
operatesFOn(3, 4) { a, b -> a + b }.also { println(it) } // prints: 7
operatesFOn(5, 7) { a, b -> a * b }.also { println(it) } // prints: 35
There are some other cool modifiers as well for higher order functions like the inline modifier.
inline fun operatesFOn(num1: Int, num2: Int, f: (Int, Int) -> Int) {
return f(num1, num2)
}
The above one will work similar but the lambda will instead be inlined at the call-site in compile time, to decrease the call-stack increasing the performance. as mentioned in the docs as well:
Using higher-order functions imposes certain runtime penalties: each function is an object, and it captures a closure, i.e. those variables that are accessed in the body of the function. Memory allocations (both for function objects and classes) and virtual calls introduce runtime overhead.

Related

Are Kotlin scope function blocks effectively inline?

I'm writing a Kotlin inline class to make Decimal4J more convenient without instantiating any objects. I'm worried that scope functions might create lambda objects, thereby making the whole thing pointless.
Consider the function compareTo in the following example.
/* imports and whatnot */
#JvmInline
value class Quantity(val basis: Long) {
companion object {
val scale: Int = 12
val metrics: ScaleMetrics = Scales.getScaleMetrics(scale)
val arithmetic: DecimalArithmetic = metrics.defaultArithmetic
}
operator fun compareTo(alt: Number): Int {
with(arithmetic) {
val normal = when (alt) {
is Double -> fromDouble(alt)
is Float -> fromFloat(alt)
is Long -> fromLong(alt)
is BigDecimal -> fromBigDecimal(alt)
is BigInteger -> fromBigInteger(alt)
else -> fromLong(alt.toLong())
}
return compare(basis, normal)
}
}
}
Does the with(arithmetic) scope create a lambda in the heap? The docs on kotlinlang.org consistently refer to the scoped code as a lambda expression. Is there any way to use scope functions without creating objects?
All of the built-in scoping functions, including with, are marked inline, which means the implementation gets planted directly in the code that's calling it. Once that happens, the lambda call can be optimized away.
To be more concrete, here's the implementation of with (with the Kotlin contracts stuff removed, since that's not relevant here)
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
return receiver.block()
}
Extension methods are, and always have been, syntax sugar resolved at compile time, so this is effectively
public inline fun <T, R> with(receiver: T, block: (T) -> R): R {
return block(receiver) // (with `this` renamed by the compiler)
}
So when we call
operator fun compareTo(alt: Number): Int {
with (arithmetic) {
println("Hi :)")
println(foobar()) // Assuming foobar is a method on arithmetic
}
}
The inline will transform this into
operator fun compareTo(alt: Number): Int {
({
println("Hi :)")
println(it.foobar()) // Assuming foobar is a method on arithmetic
})(arithmetic)
}
And any optimizer worth its salt can see that this is a function that's immediately evaluated, so we should go ahead and do that now. What we end up with is
operator fun compareTo(alt: Number): Int {
println("Hi :)")
println(arithmetic.foobar()) // Assuming foobar is a method on arithmetic
}
which is what you would have written to begin with.
So, tl;dr, the compiler is smart enough to figure it out. You don't have to worry about it. It's one of the perks of working in a high-level language.
By the way, this isn't just abstract. I just compiled the above code on my own machine and then decompiled the JVM bytecode to see what it really did. It was quite a bit noisier (since the JVM, by necessity, has a lot of noise), but there was no lambda object allocated, and the function was just one straight shot that calls println twice.
In case you're interested, Kotlin takes this example function
fun compareTo(alt: Number): Unit {
return with(arithmetic) {
println("Hi :)")
println(foobar())
}
}
to this Java, after being decompiled,
public static final void compareTo-impl(long arg0, #NotNull Number alt) {
Intrinsics.checkNotNullParameter((Object)alt, (String)"alt");
long l = arithmetic;
boolean bl = false;
boolean bl2 = false;
long $this$compareTo_impl_u24lambda_u2d0 = l;
boolean bl3 = false;
String string = "Hi :)";
boolean bl4 = false;
System.out.println((Object)string);
int n = so_quant.foobar-impl($this$compareTo_impl_u24lambda_u2d0);
bl4 = false;
System.out.println(n);
}
Quite a bit noisier, but the idea is exactly the same. And all of those pointless local variables will be taken care of by a good JIT engine.
Just some additional info to help clear up the terminology that led to your confusion.
The word “lambda” is defined as a syntax for writing a function. The word does not describe a function itself, so the word lambda has nothing to do with whether a function object is being allocated or not.
In Kotlin, there are multiple different syntaxes you can choose from to define or refer to a function. Lambda is only one of these.
// lambda assigned to variable
val x: (String) -> Unit = {
println(it)
}
// anonymous function assigned to variable
val y: (String) -> Unit = fun(input: String) {
println(input)
}
// reference to existing named function assigned to variable
val z: (String) -> Unit = ::println
// lambda passed to higher order function
“Hello World”.let { println(it) }
// anonymous function passed to higher order function
“Hello World”.let(fun(input: Any) { println(input) })
// reference to existing named function passed to higher order function
“Hello World”.let(::println)
// existing functional reference passed to higher order function
“Hello World”.let(x)
There is actually no such thing as a lambda object that can be passed around. The object is a function that could have been defined using any of the above syntaxes. Once a functional reference exists, the syntax that was used to create it is irrelevant.
With inline higher order functions, as the standard library scope functions are, the compiler optimizes away the creation of the functional object altogether. Of the four higher order calls in my example above, the first three will compile to the same thing. The last is a bit different because the function x already exists so it will be x itself that is invoked in the inlined code. Its contents don’t get hoisted out and called directly in the inlined code.
The advantage of using lambda syntax for higher order inline function calls is that it enables you to use keywords for the outer scope (non-local returns), such as return, continue, or break.

Kotlin lambdas with receivers: seeking clarification on my mental model

I'm trying to build a good mental model for lambdas with receivers in Kotlin, and how DSLs work. The simples ones are easy, but my mental model falls apart for the complex ones.
Part 1
Say we have a function changeVolume that looks like this:
fun changeVolume(operation: Int.() -> Int): Unit {
val volume = 10.operation()
}
The way I would describe this function out loud would be the following:
A function changeVolume takes a lambda that must be applicable to an Int (the receiver). This lambda takes no parameters and must return an Int. The lambda passed to changeVolume will be applied to the Int 10, as per the 10.lambdaPassedToFunction() expression.
I'd then invoke this function using something like the following, and all of a sudden we have the beginning of a small DSL:
changeVolume {
plus(100)
}
changeVolume {
times(2)
}
This makes a lot of sense because the lambda passed is directly applicable to any Int, and our function simply makes use of that internally (say 10.plus(100), or 10.times(2))
Part 2
But take a more complex example:
data class UserConfig(var age: Int = 0, var hasDog: Boolean = true)
val user1: UserConfig = UserConfig()
fun config(lambda: UserConfig.() -> Unit): Unit {
user1.lambda()
}
Here again we have what appears to be a simple function, which I'd be tempted to describe to a friend as "pass it a lambda that can have a UserConfig type as a receiver and it will simply apply that lambda to user1".
But note that we can pass seemingly very strange lambdas to that function, and they will work just fine:
config {
age = 42
hasDog = false
}
The call to config above works fine, and will change both the age and the hasDog properties. Yet it's not a lambda that can be applied the way the function implies it (user1.lambda(), i.e. there is no looping over the 2 lines in the lambda).
The official docs define those lambdas with receivers the following way: "The type A.(B) -> C represents functions that can be called on a receiver object of A with a parameter of B and return a value of C."
I understand that the age and the hasDog can be applied to the user1 individually, as in user1.age = 42, and also that the syntactic sugar allows us to omit the this.age and this.hasDog in the lambda declaration. But how can I reconcile the syntax and the fact that both of those will be run, sequentially nonetheless! Nothing in the function declaration of config() would lead me to believe that events on the user1 will be applied one by one.
Is that just "how it is", and sort of syntactic sugar and I should learn to read them as such (I mean I can see what it's doing, I just don't quite get it from the syntax), or is there more to it, as I imagine, and this all comes together in a beautiful way through some other magic I'm not quite seeing?
The lambda is like any other function. You aren't looping through it. You call it and it runs through its logic sequentially from the first line to a return statement (although a bare return keyword is not allowed). The last expression of the lambda is treated as a return statement. If you had not defined your parameter as receiver, but instead as a standard parameter like this:
fun config(lambda: (UserConfig) -> Unit): Unit {
user1.lambda()
}
Then the equivalent of your above code would be
config { userConfig ->
userConfig.age = 42
userConfig.hasDog = false
}
You can also pass a function written with traditional syntax to this higher order function. Lambdas are only a different syntax for it.
fun changeAgeAndRemoveDog(userConfig: UserConfig): Unit {
userConfig.age = 42
userConfig.hasDog = false
}
config(::changeAgeAndRemoveDog) // equivalent to your lambda code
or
config(
fun (userConfig: UserConfig): Unit {
userConfig.age = 42
userConfig.hasDog = false
}
)
Or going back to your original example Part B, you can put any logic you want in the lambda because it's like any other function. You don't have to do anything with the receiver, or you can do all kinds of stuff with it, and unrelated stuff, too.
config {
age = 42
println(this) // prints the toString of the UserConfig receiver instance
repeat(3) { iteration ->
println(copy(age = iteration * 4)) // prints copies of receiver
}
(1..10).forEach {
println(it)
if (it == 5) {
println("5 is great!")
}
}
hasDog = false
println("I return Unit.")
}

Difference between function receiver and extension function

I was reading about Kotlin and did not quite get the idea
from What I understood extension function gives ability to a class with new functionality without having to inherit from the class
and what is receiver the same except it can be assigned to variable
Is there anything else about it?
Can someone give some examples on it
Extension functions:
Like Swift and C#, Kotlin provides the ability to extend a class with new functionality without having to modify the class or inherit from the class.
You might wonder why? Because we cannot edit and add functions to the language or SDK classes. So we end up creating Util classes in Java. I believe all the projects have a bunch of *Utils classes to put the helper methods that are used at multiple places in the code base. Extensions functions help to fix this Util problem.
How do we write a helper method in Java to find whether the given long value refers to today?
public class DateUtils {
public static boolean isToday(long when) {
// logic ...
}
}
And we call that method by passing the long value as an argument:
void someFunc(long when) {
boolean isToday = DateUtils.isToday(when);
}
In Kotlin, we can extend the Long class to include the isToday() function in it. And we can call the isToday() function on the Long value itself like any other member functions in the class.
// Extension function
fun Long.isToday(): Boolean {
// logic ...
}
fun someFunc(time: Long) {
val isToday = time.isToday()
}
Compared to the Util methods, Kotlin provides a much richer syntax using the Extension functions.
This improves the readability of the code which in turns improves its maintainability. And we get a little help from the code completion of the IDE. So we don't have to remember which Util class to use for the desired function.
Under the hood, Kotlin compiler generates the static helper methods as though we had written them as Java static Util methods. So we get this nice and richer syntax in Kotlin without sacrificing any performance.
Similar to functions, Kotlin also supports extension properties where we can add a property to an existing class.
Higher order functions:
A higher-order function is a function that takes functions as parameters, or returns a function.
Lets look at how a higher order function is written.
fun execute(x: Int, y: Int, op: (Int, Int) -> Int): Int {
return op(x, y)
}
Here the third parameter ( op ) is a function and so it makes this function a higher order function. The type of the parameter op is a function that takes 2 Ints as parameter and returns a Int.
To invoke this Higher order function, we can pass a function or a lambda expression:
execute(5, 5) { a, b -> a + b }
Receiver (or Function literal with Receiver or Lambda with Recevier):
A Higher order function that takes an extension function as its parameter is called Lambda with Receiver.
Let's look at the implementation of the apply function which is available in the Kotlin standard library.
inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }
The function we pass to this apply function is actually an extension function to the type T. So in the lambda function, we can access the properties and the functions of the type T as though we are writing this function inside class T itself.
Here the generic type T is the receiver and we are passing a lambda function, hence the name Lambda with Receiver.
Another Example:
inline fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit) {
beginTransaction()
try {
func()
setTransactionSuccessful()
} finally {
endTransaction()
}
}
Here, the inTransaction() is an Extension function to the SQLiteDatabase class and the parameter of the inTransaction() function is also an extension function to the SQLiteDatabase class. Here SQLiteDatabase is the receiver, for the lambda that is passed as the argument.
To invoke that function:
db.inTransaction {
delete( ... )
}
Here the delete() is the function of the SQLiteDatabase class and since the lambda we pass is an Extension function to the receiver SQLiteDatabase we can access the delete function without any additional qualifiers with it, as though we are calling the function from inside the SQLiteDatabase class itself.
While #Bob's answer is far more informative on Kotlin than could I hope to be, including extension functions, it doesn't directly refer to the comparison between "function literals with receiver" as described in https://kotlinlang.org/docs/reference/lambdas.html#function-literals-with-receiver and extension functions (https://kotlinlang.org/docs/reference/extensions.html). I.e. the difference between:
val isEven: Int.() -> Boolean = { this % 2 == 0 }
and
fun Int.isEven(): Boolean = this % 2 == 0
The receiver part of the name refers to both of these syntaxes receiving the base Int argument as this.
As I understand it, the difference between the two is simply between one being an expression confirming to a function type and the other a declaration. Functionally they are equivalent and can both be called as:
when { myNumber.isEven() -> doSomething(myNumber) }
but one is intended for use in extension libraries, while the other is typically intended for use as an argument for a function with a function-type parameter, particularly the Kotlin builder DSLs.

What is a "receiver" in Kotlin?

How is it related to extension functions? Why is with a function, not a keyword?
There appears to be no explicit documentation for this topic, only the assumption of knowledge in reference to extensions.
It is true that there appears to be little existing documentation for the concept of receivers (only a small side note related to extension functions), which is surprising given:
their existence springing out of extension functions;
their role in building a DSL using said extension functions;
the existence of a standard library function with, which given no knowledge of receivers might look like a keyword;
a completely separate syntax for function types.
All these topics have documentation, but nothing goes in-depth on receivers.
First:
What's a receiver?
Any block of code in Kotlin may have a type (or even multiple types) as a receiver, making functions and properties of the receiver available in that block of code without qualifying it.
Imagine a block of code like this:
{ toLong() }
Doesn't make much sense, right? In fact, assigning this to a function type of (Int) -> Long - where Int is the (only) parameter, and the return type is Long - would rightfully result in a compilation error. You can fix this by simply qualifying the function call with the implicit single parameter it. However, for DSL building, this will cause a bunch of issues:
Nested blocks of DSL will have their upper layers shadowed:
html { it.body { // how to access extensions of html here? } ... }
This may not cause issues for a HTML DSL, but may for other use cases.
It can litter the code with it calls, especially for lambdas that use their parameter (soon to be receiver) a lot.
This is where receivers come into play.
By assigning this block of code to a function type that has Int as a receiver (not as a parameter!), the code suddenly compiles:
val intToLong: Int.() -> Long = { toLong() }
Whats going on here?
A little side note
This topic assumes familiarity with function types, but a little side note for receivers is needed.
Function types can also have one receiver, by prefixing it with the type and a dot. Examples:
Int.() -> Long // taking an integer as receiver producing a long
String.(Long) -> String // taking a string as receiver and long as parameter producing a string
GUI.() -> Unit // taking an GUI and producing nothing
Such function types have their parameter list prefixed with the receiver type.
Resolving code with receivers
It is actually incredibly easy to understand how blocks of code with receivers are handled:
Imagine that, similar to extension functions, the block of code is evaluated inside the class of the receiver type. this effectively becomes amended by the receiver type.
For our earlier example, val intToLong: Int.() -> Long = { toLong() } , it effectively results in the block of code being evaluated in a different context, as if it was placed in a function inside Int. Here's a different example using handcrafted types that showcases this better:
class Bar
class Foo {
fun transformToBar(): Bar = TODO()
}
val myBlockOfCodeWithReceiverFoo: (Foo).() -> Bar = { transformToBar() }
effectively becomes (in the mind, not code wise - you cannot actually extend classes on the JVM):
class Bar
class Foo {
fun transformToBar(): Bar = TODO()
fun myBlockOfCode(): Bar { return transformToBar() }
}
val myBlockOfCodeWithReceiverFoo: (Foo) -> Bar = { it.myBlockOfCode() }
Notice how inside of a class, we don't need to use this to access transformToBar - the same thing happens in a block with a receiver.
It just so happens that the documentation on this also explains how to use an outermost receiver if the current block of code has two receivers, via a qualified this.
Wait, multiple receivers?
Yes. A block of code can have multiple receivers, but this currently has no expression in the type system. The only way to achieve this is via multiple higher-order functions that take a single receiver function type. Example:
class Foo
class Bar
fun Foo.functionInFoo(): Unit = TODO()
fun Bar.functionInBar(): Unit = TODO()
inline fun higherOrderFunctionTakingFoo(body: (Foo).() -> Unit) = body(Foo())
inline fun higherOrderFunctionTakingBar(body: (Bar).() -> Unit) = body(Bar())
fun example() {
higherOrderFunctionTakingFoo {
higherOrderFunctionTakingBar {
functionInFoo()
functionInBar()
}
}
}
Do note that if this feature of the Kotlin language seems inappropriate for your DSL, #DslMarker is your friend!
Conclusion
Why does all of this matter? With this knowledge:
you now understand why you can write toLong() in an extension function on a number, instead of having to reference the number somehow. Maybe your extension function shouldn't be an extension?
You can build a DSL for your favorite markup language, maybe help parsing the one or other (who needs regular expressions?!).
You understand why with, a standard library function and not a keyword, exists - the act of amending the scope of a block of code to save on redundant typing is so common, the language designers put it right in the standard library.
(maybe) you learned a bit about function types on the offshoot.
When you call:
"Hello, World!".length()
the string "Hello, World!" whose length you're trying to get is called the receiver.
More generally, any time you write someObject.someFunction(), with a . between the object and the function name, the object is acting as the receiver for the function. This isn't special to Kotlin, and is common to many programming languages that use objects. So the concept of a receiver is likely very familiar to you, even if you haven't heard the term before.
It's called a receiver because you can think of the function call as sending a request which the object will receive.
Not all functions have a receiver. For example, Kotlin's println() function is a top-level function. When you write:
println("Hello, World!")
you don't have to put any object (or .) before the function call. There's no receiver because the println() function doesn't live inside an object.
On the receiving end
Now let's look at what a function call looks like from the point of view of the receiver itself. Imagine we've written a class that displays a simple greeting message:
class Greeter(val name: String) {
fun displayGreeting() {
println("Hello, ${this.name}!")
}
}
To call displayGreeting(), we first create an instance of Greeter, then we can use that object as a receiver to call the function:
val aliceGreeter = Greeter("Alice")
val bobGreeter = Greeter("Bob")
aliceGreeter.displayGreeting() // prints "Hello, Alice!"
bobGreeter.displayGreeting() // prints "Hello, Bob!"
How does the displayGreeting function know which name to display each time? The answer is the keyword this, which always refers to the current receiver.
When we call aliceGreeter.displayGreeting(), the receiver is aliceGreeter, so this.name points to "Alice".
When we call bobGreeter.displayGreeting(), the receiver is bobGreeter, so this.name points to "Bob".
Implicit receivers
Most of the time, there's actually no need to write this. We can replace this.name with just name and it will implicitly point to the name property of the current receiver.
class Greeter(val name: String) {
fun displayGreeting() {
println("Hello, $name!")
}
}
Notice how that differs from accessing a property from outside the class. To print the name from outside, we'd have to write out the full name of the receiver:
println("Hello, ${aliceGreeter.name}")
By writing the function inside the class, we can omit the receiver completely, making the whole thing much shorter. The call to name still has a receiver, we just didn't have to write it out. We can say that we accessed the name property using an implicit receiver.
Member functions of a class often need to access many other functions and properties of their own class, so implicit receivers are very useful. They shorten the code and can make it easier to read and write.
How do receivers relate to extensions?
So far, it seems like a receiver is doing two things for us:
Sending a function call to a specific object, because the function lives inside that object
Allowing a function convenient and and concise access to the other properties and functions that live inside the same object
What if we want to write a function that can use an implicit receiver for convenient access to the properties and functions of an object, but we don't want to (or can't) write our new function inside that object/class? This is where Kotlin's extension functions come in.
fun Greeter.displayAnotherGreeting() {
println("Hello again, $name!")
}
This function doesn't live inside Greeter, but it accesses Greeter as if it was a receiver. Notice the receiver type before the function name, which tells us that this is an extension function. In the body of the extension function, we can once again access name without its receiver, even though we're not actually inside the Greeter class.
You could say that this isn't a "real" receiver, because we're not actually sending the function call to an object. The function lives outside the object. We're just using the syntax and appearance of a receiver because it makes for convenient and concise code. We can call this an extension receiver, to distinguish it from the dispatch receiver that exists for functions that are really inside an object.
Extension functions are called in the same way as member functions, with a receiver object before the function name.
val aliceGreeter = Greeter("Alice")
aliceGreeter.displayAnotherGreeting() // prints "Hello again, Alice!"
Because the function is always called with an object in the receiver position before the function name, it can access that object using the keyword this. Like a member function, an extension function can also leave out this and access the receiver's other properties and functions using the current receiver instance as the implicit receiver.
One of the main reasons extension functions are useful is that the current extension receiver instance can be used as an implicit receiver inside the body of the function.
What does with do?
So far we've seen two ways to make something available as an implicit receiver:
Create a function inside the receiver class
Create an extension function outside the class
Both approaches require creating a function. Can we have the convenience of an implicit receiver without declaring a new function at all?
The answer is to call with:
with(aliceGreeter) {
println("Hello again, $name!")
}
Inside the block body of the call to with(aliceGreeter) { ... }, aliceGreeter is available as an implicit receiver and we can once again access name without its receiver.
So how come with can be implemented as a function, rather than a language feature? How is it possible to simply take an object and magic it into an implicit receiver?
The answer lies with lambda functions. Let's consider our displayAnotherGreeting extension function again. We declared it as a function, but we could instead write it as a lambda:
val displayAnotherGreeting: Greeter.() -> Unit = {
println("Hello again, $name!")
}
We can still call aliceGreeter.displayAnotherGreeting() the same as before, and the code inside the function is the same, complete with implicit receiver. Our extension function has become a lambda with receiver. Note the way the Greeter.() -> Unit function type is written, with the extension receiver Greeter listed before the (empty) parameter list ().
Now, watch what happens when we pass this lambda function as an argument to another function:
fun runLambda(greeter: Greeter, lambda: Greeter.() -> Unit) {
greeter.lambda()
}
The first argument is the object that we want to use as the receiver. The second argument is the lambda function we want to run. All runLambda does is to call the provided lambda parameter, using the greeter parameter as the lambda's receiver.
Substituting the code from our displayAnotherGreeting lambda function into the second argument, we can call runLambda like this:
runLambda(aliceGreeter) {
println("Hello again, $name!")
}
And just like that, we've turned aliceGreeter into an implicit receiver. Kotlin's with function is simply a generic version of this that works with any type.
Recap
When you call someObject.someFunction(), someObject is acting as the receiver that receives the function call
Inside someFunction, someObject is "in scope" as the current receiver instance, and can be accessed as this
When a receiver is in scope, you can leave out the word this and access its properties and functions using an implicit receiver
Extension functions let you benefit from the receiver syntax and implicit receivers without actually dispatching a function call to an object
Kotlin's with function uses a lambda with receiver to make receivers available anywhere, not just inside member functions and extension functions
Kotlin knows the concept of a function literals with receiver. It enables access on visible methods and properties of a receiver of a lambda within its body without having to use any additional qualifier. That's very similar to extension functions in which you can as well access members of the receiver object inside the extension.
A simple example, also one of the greatest functions in the Kotlin standard library, is apply:
public inline fun <T> T.apply(block: T.() -> Unit): T {
block()
return this
}
Here, block is a function literal with receiver. This block parameter is executed by the function and the receiver of apply, T, is returned to the caller. In action this looks as follows:
val foo: Bar = Bar().apply {
color = RED
text = "Foo"
}
We instantiate an object of Bar and call apply on it. The instance of Bar becomes the receiver of apply. The block, passed as an argument in curly brackets does not need to use additional qualifiers to access and modify the properties color and text.
The concept of lambdas with receiver is also the most important feature for writing DSLs with Kotlin.
var greet: String.() -> Unit = { println("Hello $this") }
this defines a variable of type String.() -> Unit, which tells you
String is the receiver
() -> Unit is the function type
Like F. George mentioned above, all methods of this receiver can be called in the method body.
So, in our example, this is used to print the String. The function can be invoked by writing...
greet("Fitzgerald") // result is "Hello Fitzgerald"
the above code snippet was taken from Kotlin Function Literals with Receiver – Quick Introduction by Simon Wirtz.
Simply put ( without any extra words or complications) , the "Receiver" is the type being extended in the extension function or the class name. Using the examples given in answers above
fun Foo.functionInFoo(): Unit = TODO()
Type "Foo" is the "Receiver"
var greet: String.() -> Unit = { println("Hello $this") }
Type "String" is the "Receiver"
Additional tip: Look out for the Class before the fullstop(.) in the "fun" (function) declaration
fun receiver_class.function_name() {
//...
}
Simply put:
the receiver type is the type an extension function extends
the receiver object is the object an extension function is called on; the this keyword inside the function body corresponds to the receiver object
An extension function example:
// `Int` is the receiver type
// `this` is the receiver object
fun Int.squareDouble() = toLong() * this
// a receiver object `8` of type `Int` is passed to the `square` function
val result = 8.square()
A function literal example, which is pretty much the same:
// `Int` is the receiver type
// `this` is the receiver object
val square: Int.() -> Long = { toLong() * this }
// a receiver object `8` of type `Int` is passed to the `square` function
val result1 = 8.square()
val result2 = square(8) // this call is equal to the previous one
The object instance before the . is the receiver. This is in essence the "Scope" you will define this lambda within. This is all you need to know, really, because the functions and properties(varibles, companions e.t.c) you will be using in the lambda will be those provided within this scope.
class Music(){
var track:String=""
fun printTrack():Unit{
println(track)
}
}
//Music class is the receiver of this function, in other words, the lambda can be piled after a Music class just like its extension function Since Music is an instance, refer to it by 'this', refer to lambda parameters by 'it', like always
val track_name:Music.(String)->Unit={track=it;printTrack()}
/*Create an Instance of Music and immediately call its function received by the name 'track_name', and exclusively available to instances of this class*/
Music().track_name("Still Breathing")
//Output
Still Breathing
You define this variable with and all the parameters and return types it will have but among all the constructs defined, only the object instance can call the var, just like it would an extension function and supply to it its constructs, hence "receiving" it.
A receiver would hence be loosely defined as an object for which an extension function is defined using the idiomatic style of lambdas.
Typically in Java or Kotlin you have methods or functions with input parameters of type T. In Kotlin you can also have extension functions that receive a value of type T.
If you have a function that accepts a String parameter for example:
fun hasWhitespace(line: String): Boolean {
for (ch in line) if (ch.isWhitespace()) return true
return false
}
converting the parameter to a receiver (which you can do automatically with IntelliJ):
fun String.hasWhitespace(): Boolean {
for (ch in this) if (ch.isWhitespace()) return true
return false
}
we now have an extension function that receives a String and we can access the value with this

Does Kotlin have an identity function?

Scala has a generic identity function in the Predef:
def identity[A](x: A): A
Does Kotlin have a similar facility in the standard library? Of course I could simply use { it } instead, but I find identity easier to read, and instantiating all those lambdas is a little wasteful.
I must be able to use this identity function in places where a function (Foo) -> Foo is expected, for any type Foo. Is such a function even possible in Kotlin's type system? (In the case of Scala, there is an implicit conversion that wraps the method inside a function object or something.)
If you need to pass the identity function as a parameter to another function, you can simply use { it }. For example, it you have a List<List<String>> and want to flatten it to a List<String>, you could use:
list.flatMap(identity)
where identity is the identity function. This can be written as:
list.flatMap { it }
This is equivalent to:
list.flatMap { x -> x }
The alternative would be to define the identity function somewhere, such as:
val identity: (List<String>) -> List<String> = { it }
But we can't create a generic val, so we would have to define an identity function for each type. The solution, (as it is done in Java Function interface) is to define it as a constant function:
fun <A> identity(): (A) -> A = { it }
and use it as:
list.flatMap(identity)
Of course, it is much easier to write:
list.flatMap { it }
Declaring an identity function once for all (that would work for all types) is not possible because it would have to be parameterized. What is possible is to use a function returning this identity function:
fun <T> identity(): (T) -> T = { it }
Although it does the job, it is not very helpful since one has now to write:
list.flatMap(identity())
There's no such function at the moment, but you can easily define it yourself:
fun <T> identity(x: T): T = x
If you think there are enough use cases for this function to be declared in Kotlin standard library, please file an issue at youtrack.jetbrains.com. Thanks!