The Programmers Guide To Kotlin - Type
The Programmers Guide To Kotlin - Type
Written by Mike James   
Monday, 06 November 2017
Article Index
The Programmers Guide To Kotlin - Type
Casting

UnSafe and Safe Casting

Casting is the general practice of treating one object as if it was an object of another type. 

In fact casting is slightly more subtle than this as it involves an object of a given type and a variable that references the object which can be of a different declared type. 

If you find you are having problems understanding casting then make sure that you keep in mind the following:

There are always two possible types to consider. The type of the variable used to reference an object and the type of the object being referenced. These need not be the same. 

For example consider:

var myObjectA:MyClassA

this declares the variable myObjectA to be of type MyClassA but at the moment it doesn't reference anything.

If we keep things very simple it could only reference an object of type MyClassA but this would be very restrictive. As an object of MyClassB has all of the methods and properties of MyClassA objects, we can allow the variable myObjectA to reference an object of MyClassB. 

 

ref

The variable myObjectA can reference an object of type MyClassB by referencing the instance of MyClassA within.

 

In other words:

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

Put another way upcasting is a safe operation. 

Kotlin allows you to cast an object to a new type using the as operator. 

So as long as myObjectB has been created: 

val myObjectB=myClassB()

Then, for example, we can say:

myObjectA = myObjectB as MyClassA

Now myObjectA actually references an object of type MyClassB, but this doesn't matter as all of the methods that you can use are present in myObjectB.

This cast is safe but only because MyClassB is a derived class of MyClassA. If this wasn't the case then there would be an exception. So this sort of cast isn't safe. You can make it safe using the safe cast operator which casts to a nullable type: 

var myObjectA:MyClassA?
myObjectA = myObjectB as? MyClassA

Now if myObjectB turns out not to be derived from MyClassA, myObjectA is set to null. Notice that you have to declare myObjectA as a nullable type, i.e. as MyClass?, and from this point on you have to play by the rules of nullable types. 

 

kotlinlogo

Down Casting

If there is up casting, when you treat a derived class is it it was the base class, there is also down casting, which is where you use a variable of a base class type to reference a derived type and then cast to that derived type. 

The first question that usually comes to mind is, why would you want to do this?

The answer is that you use this technique when you need to apply an algorithm to types of the base class and all derived classes. 

For example, if you need to sort some objects into order, you could use a variable of type Any to reference any object. 

For example:

var myVariable:Any
myVariable=anyObject

myVariable can be used to reference any type as all types are sub-types of Any. This is an up cast even if it is the most extreme up cast possible. The down cast comes into the picture when, after doing whatever you want to with the objects of any type, you can down cast to make use of one of their properties. 

For example:

val myObjectB=MyClassB()
val myObject:Any=myObjectB
(myObject as MyClassB).myFunctionB()

here we create an instance of MyClassB and then set myObject to reference it. As myObject is of type Any you can't use it to call any of the methods of MyClassB. However, if we down cast it to the MyClassB type we can now call its methods. 

Of course if myObject isn't referencing an instance of MyClassB, this will fail with an exception. You can use the safe cast to get a null, however.

Down casting and using Any references is a way of implementing generics when you don't have generics. An array of Any will hold references to any type of object and so you can use this to implement "generic" collections. In languages that do have generics, such as Kotlin, you really should be able to avoid using a down cast.  

Another use of down casting is when you pass a base type parameter to a function and then down cast to the particular derived type that has been supplied. 

 

Programmer's Guide To Kotlin

Now Available as a Print Book

cover

You can buy it from:

USA and World     Amazon.com
Canada            Amazon.ca

UK                Amazon.co.uk
France            Amazon.fr
Germany           Amazon.de
Spain             Amazon.es
Italy             Amazon.it

 

 

Contents
Some Chapters Already Available On The Web

  1. What makes Kotlin Special (Book Only)
  2. The Basics: Variables, Primitive Types and Functions
  3. Control
  4. Strings and Arrays
  5. The Class & The Object
  6. Inheritance
  7. The Type Hierarchy 
    Extract 1 Type and its problems **NEW!**
  8. Generics
  9. Collections, Iterators, Sequences & Ranges
                                               (Coming soon!)
  10. Advanced functions 
  11. Anonymous, Lamdas & Inline Functions
  12. Data classes, enums and destructuring
    Extract 1 Data Classes  **NEW!**
  13. Exceptions, Annotations & Reflection
  14. Working with Java

 

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, FacebookGoogle+ or Linkedin.

 

Banner


SciPy1.0 Released
26/10/2017

SciPy, the widely used open source Python library used for scientific and technical computing, has reached the milestone of a Version 1.0 release. This maturity is completed by a governance model [ ... ]



Atom Adds Collaborative Coding
22/11/2017

GitHub's Atom text editor has a new feature, currently in beta, for collaborative coding. Teletype for Atom lets you write and edit code with other developers in real-time.


More News

 
 

 

blog comments powered by Disqus

 <ASIN:1871962536>

 



Last Updated ( Monday, 06 November 2017 )
 
 

   
Banner
Banner
RSS feed of all content
I Programmer - full contents
Copyright © 2017 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.