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

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. 



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. 



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


You can buy it from:

USA and World




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  Type and its problems
  8. Generics
             Extract  Basic Generics **NEW!**
  9. Collections, Iterators, Sequences & Ranges
             (Coming soon!)
  10. Advanced functions 
  11. Anonymous, Lamdas & Inline Functions
  12. Data classes, enums and destructuring
             Extract  Data Classes 
  13. Exceptions, Annotations & Reflection
             Extract Annotation & 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.



AI Predicts World Cup Winners

An AI system has been used to calculate the likely winners of this year's FIFA World Cup; and the real shock is the system didn't pick Germany. The FIFA World Cup 2018 is underway at the moment in Rus [ ... ]

TypeScript Adds Unused Span Reporting

The latest release of TypeScript is now available with improvements to the editor including support for unused span reporting; the ability to convert properties to getter/setter; and the choice of mov [ ... ]

More News





or email your comment to:



Last Updated ( Monday, 06 November 2017 )

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