The Programmers Guide To Kotlin - Anonymous and Lambda Functions |
Written by Mike James | ||||
Monday, 29 October 2018 | ||||
Page 1 of 3 Languages that don't allow functions to exist as entities in their own right make things difficult without many advantages. Kotlin introduces features to allow functions to be treated in more flexible ways, in particular to be used as parameters to other functions. Programmer's Guide To Kotlin Third Edition
You can buy it from: Amazon Contents
<ASIN:B0D8H4N8SK> Many of Kotlin's language innovations are about how you can use functions. As well as being able to use standalone "classical" functions, Kotlin also provides function expression and references, which allow you to pass functions to other functions. One of the problems is that this has resulted in a confusing menagerie of new and different function types. When it comes to functions in Kotlin, there is usually more than one way to get a particular job done. Anonymous Functions & ReferencesWhat isn't as well known as it should be, is that you can create a variable of a function type and you can store a reference to a function in it. For example:
Notice that the function isn't anything new like a lambda function, it is just a standard function that doesn't have a name – an anonymous function. An anonymous function is just like any other function and can have named parameters, default values and so on. The only real difference is that it doesn't have a name and so can't be invoked in the usual way. However, you can store a reference to it in a variable of the correct type and invoke it using the usual () operator. What is even less well known is that you can use a named function in the same way, i.e. as a function reference. You can't simply assign a named function to a variable of the correct type because Kotlin demands that, if you just use the name of a function, you are invoking it and have to provide arguments and handle the return type. For example, if you try:
you will get an error message saying that you haven’t invoked the function with arguments, i.e the compiler is expecting sum(1,2) or similar. However, if you make use of the :: reflection reference operator then you can obtain a reference to the function. That is:
works and it does store a reference to sum in myfunc which can then be used to call the function:
You can pass an anonymous function as an argument to another function and using the :: operator you can pass a reference to a named function in the same way. For example if you define a function which accepts an arith function type, executes it, and prints the result:
then you can call it and pass the anonymous myfunc:
or the named sum function:
|
||||
Last Updated ( Saturday, 03 November 2018 ) |