When do I use another function without paramters in Kotlin? - kotlin

I'm a novice of Kotlin.
I found that I can use another function without parameters even if it has.
Let me know when I can use it.
Q1) Why can I use 2 types? (with parameters & without parameters) Is it Kotlin's feature?
Q2) What does it mean? ((Result!) -> Unit)!

It seems you are confused, you can never use a function without arguments. If the function has arguments then you have to fill the slot somehow.
The closest thing that could relate to what you are referring to is default values for arguments.
fun example(boolean: Boolean = true) {}
example()
example(true)
example(false)
You can omit the argument because it has defaulted in the function signature.
The documentation
What you are showing in the image file is a lambda.
In the first example:
signIn(listener: Session...)
That seems to be a callback. So it is gonna be an interface or maybe an abstract class called when some async operation is finished.
The second example, it is the callback implemented as a lambda
signIn() { result ->
//do something
}
In Kotlin the last argument if it is a lambda or something that can be implemented as a lambda can be moved out of the parenthesis for syntactic sugar. A lambda is like an anonymous function, it is a literal of a function.
By example you can declare a lambda:
val lambda = {text: String -> text.lenght % 2 == 0}
fun setRuleForText(rule: (String)-> Boolean) {...}
setRuleForText(lambda)
setRuleForText() { text: String
text.isNotEmpty()
}
In this case, the argument is a kotlin function. The argument rule is a function that receives a String as an argument and returns Boolean. Something to point out is that expressions return the last written value without the need for the reserved return word.
This is the documentation. And here you can see from a good source more about functions (the author is a Kotlin certified trained by Jetbrains)
In your case (Result) -> Unit means the lambda should receive a Result type as argument and then return Unit (unit is like void in Java but is more than that), no explicit return type.
signIn() { result ->
//do something
}
Most of the types, the argument on lambdas is inferred automatically, but if not, then
signIn() { result: Result ->
//do something
}

Both of the listed functions take a parameter.
The first is:
signIn(listener: Session.SignInListener!)
That takes a single parameter, of type Session.SignInListener.  (The ! means that Kotlin doesn't know whether it's nullable or not, because it's from Java and isn't annotated.)
The other is:
signIn {...} (listener: ((Result!) -> Unit)!)
That's the IDE's representation of the function with this signature:
signIn(listener: ((Result!) -> Unit)!)
That takes a single parameter, which is a function type (see below).
The reason the IDE shows it with braces is that in Kotlin, if the last parameter to a function is a lambda, you can move it outside the parentheses.  So a call like this:
signIn({ println(it) })
could equally well be written like this:
signIn() { println(it) }
The two forms mean exactly the same.  And, further, if the lambda is the only parameter, you can omit the parens entirely:
signIn { println(it) }
Again, it means exactly the same thing.
That syntax allows you to write functions that look like new language syntax.  For example:
repeat (10) {
// ...
}
looks like a new form of loop construct, but it's really just a function called repeat, which takes two parameter (an integer, and a lambda).
OK, let's look at that function type: ((Result!) -> Unit)!
That's the type of a function which takes one parameter of type Result, and returns Unit (i.e. nothing useful; think of it as the equivalent of void).  Again, it's complicated because Kotlin doesn't know about the nullability; both the Result parameter and the parameter holding this function have !s to indicate this.  (Without them, it would just be (Result) -> Unit.)

Related

In kotlin what is this syntax: "fun ClassName.funcName(): (Type ) -> Type = {fun body}"

Edited: What and how it work? This is a kotlin dsl language.
fun ClassName.funcName(): (Type ) -> Type = {func body}
um this is one of the implementation I found, and also see the concrete syntax to this link: https://dzone.com/articles/the-complete-custom-gradle-plugin-building-tutoria
private fun CodeLinesExtension.buildFileFilter():
(File) ->
Boolean =
if (fileExtensions.isEmpty()) {
{ true }
} else {
{ fileExtensions.contains(it.extension) } // filter by extension
}
if you CALL this one as a arguments in ".filter(...)", what would happed in the "(File)" syntax, is it automatically receive an arguments?
someFiles.filter(CodeLinesExtension.buildFileFilter()).forEach{...}
There are many things at play here.
fun SomeClass.funcName() is the syntax for declaring extension functions. These are used just like regular methods of the class SomeClass, but can be defined outside of the class, and it's especially useful on classes that you don't control.
The return type of the function you mention is (File) -> Boolean. This expression describes a function type. In this specific case, it is the type of all functions that take a File as single argument, and return a Boolean.
This means that your buildFileFilter() function is an extension function that itself returns a function (File) -> Boolean.
As you can see in the function's body, inside the if statement, there are braces to define the blocks of the if-else ({ ... }), but also braces inside those blocks. This is because Kotlin uses braces for lambda expressions (literals for anonymous functions).
{ true } is a lambda expression that represents a function that may or may not take arguments, but returns true every time.
So this code:
if (fileExtensions.isEmpty()) {
{ true }
} else {
{ fileExtensions.contains(it.extension) } // filter by extension
}
returns either:
{ true } - a function that takes a File as argument and always returns true, or
{ fileExtensions.contains(it.extension) } - a function that takes a File as argument and returns whether fileExtensions contains the extension of the File that it receives (it is the implicit name for the File argument)
Note: the fact that these functions take a File as argument is inferred by the compiler based on the return type of buildFileFilter().
if you CALL this one as a arguments in ".filter(...)", what would happed in the "(File)" syntax, is it automatically receive an arguments?
filter() itself actually expects a function as argument. The function you pass to filter() is called a predicate, because it takes one element of the list as argument and returns a Boolean that says whether this element should be included in the resulting list.
So if you apply filter to a List<File>, the predicate expected by filter is exactly of type (File) -> Boolean (it says whether we should put this File item in the resulting collection).
Calling buildFileFilter() returns a function as we have seen, and the function is perfectly of the right type to use it in filter. The File argument of the function returned by buildFileFilter() will be given by the filter function itself when it calls your filter function.

Higher order functions is complex?

I have read many articles, but there are still things I am having difficulty understanding. Where's the point I can't understand? My questions are in the code. I hope I asked right.
fun main() {
/*
1- Is it argument or parameter in numbers{} block?
where is it sent to the argument? why do we send "4" if it is parameter?
Are all the functions I will write in (eg println) sent to the numbers function? But this HOF can
only take one parameter.
*/
numbers {
/*
2-How does this know that he will work 3 times?
According to the following 3 functions? Is there a for loop logic??
*/
println(it)
"4" // 3- Which one does this represent? f:(String) or ->String?
}
}
fun numbers(f: (String) -> String) {
f("one")
f("two")
f("three")
println(f(" - "))
}
There is no argument or parameter defined in your lambda block above. It's just the content of your lambda function. You've used the implicit single parameter name of it. "4" is the return value of your lambda.
The lambda itself isn't "aware" of how many times it will be called. In this case, it is called four times, because your numbers function invokes the parameter f four times.
A lambda's return value is whatever its last expression evaluates to. In this case, it returns the String "4".
Maybe this will help. Lambda syntax is a convenience. But we can take away each piece of syntactic sugar one at a time to see what it actually means.
All of the code blocks below have the exact same meaning.
Here is your original statement:
numbers {
println(it)
"4"
}
First, when a lambda omits the single parameter, it gets the implicit parameter name it. If we avoid using this sugar, it would look like this:
numbers { inputString ->
println(inputString)
"4"
}
The evaluated value of the last expression in a lambda is what it returns. You can also explicitly write a return statement, but you must specify that you are returning from the lambda, so you have to put its name. So if we put this in, it looks like this:
numbers { inputString ->
println(inputString)
return#numbers "4"
}
When a lambda is the last argument you pass to a function, you can put it outside the parentheses. This is called "trailing lambda". And if the function is the only argument, you don't need parentheses at all. If we skip this convenience, it looks like this:
numbers({ inputString ->
println(inputString)
return#numbers "4"
})
A lambda is just a very compact way of defining a function. If we define the function directly, it looks like this:
numbers(fun(inputString: String): String {
println(inputString)
return "4"
})
The function you are passing is the argument of the numbers() function. You can also define it separately and then pass the function reference like this:
fun myFunction(inputString: String): String {
println(inputString)
return "4"
}
numbers(::myFunction)

How does Kotlin recognize a lambda receiver in a "use" function

When I look at sample code for the "use" function in Kotlin, I usually see something like this:
private fun readFirstLine(): String {
BufferedReader(FileReader("test.file")).use { return it.readLine() }
}
However, in the following example, I don't understand where "input" comes from, since input -> appears to be a lambda. From my understanding, everything inside of use { } must be an expression:
val streamIn = resources.openRawResource(rawResId)
val streamOut = FileOutputStream(destFilename)
streamIn.use { input ->
streamOut.use { output ->
input.copyTo(output)
}
}
"input" clearly refers to the same object that "streamIn" refers to, but I don't understand how Kotlin knows that.
everything inside of use { } must be an expression
If you looked at the signature, you'll see that use takes a (T) -> R function, so really, any function/lambda that accepts the closable thing as a parameter can be passed to it.
With that misconception cleared up, let's see what the code in question is doing.
streamIn.use { input ->
streamOut.use { output ->
input.copyTo(output)
}
}
First we see streamIn.use {, which means we are going to do something with streamIn and then close it. And from now on streamIn will be called input. Then there is streamOut.use {, which indicates that we are also going to use streamOut to do stuff, and then close it, and we are going to call it output from now on.
I don't understand where "input" comes from
It's basically giving another name to the it as in your first code snippet. Since we have nested lambdas here, we can't use it to refer to the parameters of both lambdas.
"input" clearly refers to the same object that "streamIn" refers to, but I don't understand how Kotlin knows that.
This is because in the implementation of use, there's probably a line like this:
return block(this)
block is the lambda parameter you pass to use, and this is the object on which use is called. Since input is the parameter of the lambda, it refers to this.
Now we have declared that we are going to use two resources, what are going to do with them? input.copyTo(output)! Whatever copyTo returns is going to be returned by streamOut.use, which in turn is going to be returned by streamIn.use. streamOut and streamIn will also be closed one after another.
So overall what have we done? We have basically used 2 resources at the same time and closed them afterwards. This is how you'd compose use to use multiple resources at the same time.
in the lambda, you can define a name for your object so in the following code the input is equivalent to it which is streamIn and output is equivalent to streamOut:
streamIn.use { input ->
streamOut.use { output ->
input.copyTo(output)
}
}
The reason that they define input and output is you cannot use it when you use a lambda block inside another lambda block.
use is an extension function which takes whatever calls it as a parameter.
Assume this example:
file.bufferedReader().use{
println(it.readText()) // it is actually that object that calls `use`
}
According to the API docs of Kotlin, this is the schema of use:
inline fun <T : AutoCloseable?, R> T.use(block: (T) -> R): R
The bufferedReader in my example is a closable class.
When you write somethingClosable.use { }, you are in fact passing a lambda function to it, like:
fun <T, R> function(t: T): R {
// use T and return an R
}
somethingClosable.use(function)
And inside use your function will be called.
More info on extension functions in Kotlin.

what actually param(this.otherParam) means in kotlin? [duplicate]

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

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