| The Programmers Guide To Kotlin - Smart Casts |
| Written by Mike James | ||||||
| Monday, 13 May 2019 | ||||||
Page 2 of 2
Function TypesOne big difference between Kotlin and other more traditional object oriented languages is that it allows you to treat functions as types. This is necessary when you allow for functions which are not methods such as lambdas. If you can pass a function as a parameter you need to specify its type. The type of a function is just its signature plus its return type. For example: (Int,String)->Unit is a function type that accepts an Int and a String and returns Unit. You can use function types to define variables and parameters which can be used to reference a function of that type. For example: val add:(Int,Int)->Int
add = {a:Int,b:Int->a+b}
println(add(1,2))
This declares a variable called add which can be a reference to a function that takes two Ints and returns an Int. The next line defines just such a function and the final line makes use of it. Function types can be difficult to read and it is usually a good idea to use a type alias to make their meaning more obvious. Type AliasesOne of the big problems in programming is naming. You need to use descriptive names but usually this mean very long names. How often you find class names like: class NewCustomerInTheNorthernSector{
You can use a typealias to add a shortened form of the name: typealias NCusNorth=NewCustomerInTheNorthernSector You could, but it probably isn't a good idea. Short names are usually bad and having two names for something is usually even worse. Notice that a typealias cannot be local or nested within another structure. There is some justification for using typealias in connection with generics as their names tend to become very long due to the need to repeat type parameters. Another good use is to give a meaningful name to a function type. For example in the previous section we had a function which accepted two Ints and return an Int. We can make this more descriptive by defining a typealias: typealias arithmetic=(Int,Int)->Int Now we can define the add function as: val add: arithmetic which gives you a much clearer idea of what the function is for, even if it gives you a poorer idea of what its signature is.
Summary
This article is an extract from: Programmer's Guide To Kotlin Third Edition
|
Visualize The Inner Workings Of An LLM 17/10/2025 Simply referred to as "LLM Visualization" this web site |
Insectile Garments For Dutch Design Week 19/10/2025 FashionTech is a field that blends haute couture design and mechatronics engineering. It is also something you can study at as part of an undergraduate degree at the Eindhoven University of Tech [ ... ] |
More News
|
Comments
or email your comment to: comments@i-programmer.info
<ASIN:1871962536>
<ASIN:1871962544>



