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


Copilot Improves Code Quality
27/11/2024

Findings from GitHub show that code authored with Copilot has increased functionality and improved readability, is of better quality, and receives higher approval rates than code authored with it.



Visual Studio 17.12 Released Along With Aspire
25/11/2024

Visual Studio 2022 v17.12 is now available. The release can be used for .NET 9 projects and has a range of other improvements.


More News

espbook

 

Comments




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

 <ASIN:1871962536>

 



Last Updated ( Monday, 06 November 2017 )