|The Programmers Guide To Kotlin: Advanced Functions|
|Written by Mike James|
|Monday, 11 September 2017|
Page 3 of 3
A very nice and very simple syntactic transformation is to convert:
This allows you to write functions as infix operators.
This only works for methods, of course, and extension functions because it has to be possible to call the function with a sensible this value. It also only works with functions with a single parameter.
For example, we can define an infix extension function’s sum:
Now we can write:
and get the result 3.
It is obvious, from the fact that you can use a function call in an expression, that infix functions can be used in expressions in a natural manner.
is seven as multiplication has a higher priority than a function call.
In most cases all you really need to know is the signature of a function, i.e. what the types are of its parameters and perhaps its return type. The signature of a function is used to determine which function is called if there are a number of overloads.
Sometimes, however, we need to define a type that corresponds to a particular signature and return type. For this we need to create a specific function type.
defines a function type that takes a String and returns an Int.
defines a function type that takes two Ints and returns an Int. As already introduced in Chapter 7 we can define a type alias to avoid having to type out a function type definition each time it is needed.
Defines the arith type to be a function that takes two Ints and returns an Int.
The only not quite obvious function type is:
which is the type of a function taking no parameters and returning no result.
Programmer's Guide To Kotlin Second Edition
You can buy it from: Amazon
or email your comment to: firstname.lastname@example.org
|Last Updated ( Monday, 11 September 2017 )|