Reputation: 1222
I am going through the Kotlin exercises on GitHub (see link below).
I don't quite understand the following code.
Specifically
Where is the mouse listener created?
How does mouseListener
get invoked? It is invoked 4 times. I didn't see this syntax before. It will be great if you could point to the documentation.
// this code is on the github and is working val result = task10 { mouseListener -> mouseListener.mouseClicked(mouseEvent) mouseListener.mouseClicked(mouseEvent) mouseListener.mouseClicked(mouseEvent) mouseListener.mouseClicked(mouseEvent) }
I am thinking the code should be written like the following. However if I ran, no event gets triggered.
// this is not working
val result = task10 {
mouseListener ->
{
mouseListener.mouseClicked(mouseEvent)
mouseListener.mouseClicked(mouseEvent)
mouseListener.mouseClicked(mouseEvent)
mouseListener.mouseClicked(mouseEvent)
}
}
The full declaration of the method is:
fun task10(handleMouse: (MouseListener) -> Unit): Int {
var mouseClicks = 0
handleMouse(todoTask10())
return mouseClicks
}
Full source code is here and here.
Thank you in advance.
Upvotes: 1
Views: 732
Reputation: 1222
It actually is called type safe builder in Kotlin. See the detailed explanation here.
http://kotlinlang.org/docs/reference/type-safe-builders.html
The relevant paragraph I cut and paste it below
... So, what does this call do? Let’s look at the body of html function as defined above. It creates a new instance of HTML, then it initializes it by calling the function that is passed as an argument (in our example this boils down to calling head and body on the HTML instance), and then it returns this instance. This is exactly what a builder should do. ...
That is exactly what it does in the code that calls task10 function.
Upvotes: 1
Reputation: 8453
In most case curly braces means lambda declaration (when it's not part of other declaration). I.e. second example pass to task10
lambda which returns lambda.
You can find more information in the reference
Note: you should get warning on inner lambda from IDE and compiler.
Upvotes: 1