The Programmers Guide To Kotlin: Advanced Functions |
Written by Mike James | |||||||
Monday, 11 September 2017 | |||||||
Page 3 of 3
Infix FunctionsA very nice and very simple syntactic transformation is to convert:
into
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. For example:
is seven as multiplication has a higher priority than a function call. Function TypesIn 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. For example:
defines a function type that takes a String and returns an Int. Similarly:
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. For example:
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. Summary
Programmer's Guide To Kotlin Third Edition
You can buy it from: Amazon Contents
<ASIN:B0D8H4N8SK>
To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info <ASIN:1871962536>
|
|||||||
Last Updated ( Monday, 11 September 2017 ) |