The Programmers Guide To Kotlin - Smart Casts
Written by Mike James   
Monday, 13 May 2019
Article Index
The Programmers Guide To Kotlin - Smart Casts
Function Types

Function Types

One 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 Aliases

One 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
add = {a:Int,b:Int->a+b}
println(add(1,2))

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. 

kotlinlogo

Summary

  • The idea of type arises from the different ways that apparently the same data can be represented e.g. “2” and 2.

  • This idea has been extended into a complex system of hierarchical types based on class and inheritance.

  • A derived class can (nearly) always be used in place of a base class.

  • A variable of one type can be used to reference a class of a different but related type.

  • Changing type from a derived type to a base type is called up casting and is generally a safe operation.

  • Changing type from a base class to a derived type is called down casting and is only safe if the base class is of the type you are casting to.

  • Kotlin provides smart casting which will cast to the type you have just tested for.

  • You can test an object type using is or !is.

  • You can explicitly cast to another type using as or the safe type operator as?

  • All methods in Kotlin are what would be called “virtual” in some other languages. This means that the method called depends on the runtime type of the object referenced, and not the compile time type of the variable doing the referencing.

  • You can define function types as (parameter types) ->return type

  • A typealias assigns a name to a type.

This article is an extract from: 

Programmer's Guide To Kotlin Third Edition

kotlin3e360

You can buy it from: Amazon

Contents

  1. What makes Kotlin Special
  2. The Basics:Variables,Primitive Types and Functions 
  3. Control
         Extract: If and When 
  4. Strings and Arrays
  5. The Class & The Object ***NEW!
  6. Inheritance
  7. The Type Hierarchy
  8. Generics
  9. Collections, Iterators, Sequences & Ranges
        Extract: Iterators & Sequences 
  10. Advanced functions 
  11. Anonymous, Lamdas & Inline Functions
  12. Data classes, enums and destructuring
        Extract: Destructuring 
  13. Exceptions, Annotations & Reflection
  14. Coroutines
        Extract: Coroutines 
  15. Working with Java
        Extract: Using Swing
  16. Compose Multiplatform
        Extract: Compose Layout 

<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.

Banner


Raspberry Pi CM5 - Expensive And Undocumented
27/11/2024

So the unexpected has happened - the Compute Module 5 has been launched. But it simply emphasises some problems with adopting the Pi as an IoT device.



Apache Fury Adds Optimized Serializers For Scala
31/10/2024

Apache Fury has been updated to add GraalVM native images and with optimized serializers for Scala collection. The update also reduces Scala collection serialization cost via the use of  encoding [ ... ]


More News

espbook

 

Comments




or email your comment to: comments@i-programmer.info

<ASIN:1871962536>

<ASIN:1871962544>



Last Updated ( Monday, 17 June 2019 )