Type casting

Converting data from one type to another is called type casting, for example, conversion from Float to Integer, or from Double to String. With Java or C++, type casting is a very straightforward process because these languages have primitive data types. Look at the following Java example:

double d = 10.50;
int i = (int) d;

In Kotlin, everything is an object and so it requires some extra steps to type cast from one type to another. However, Kotlin provides a rich library that helps perform these conversions. Let's explore this with the following example. Create a Byte variable and assign a value of 10 to it. Create an Integer variable and attempt to assign byteValue to intValue:

var byteValue : Byte = 10
var intValue : Int
intValue = byteValue

Since the data types are different, the preceding code block will throw a type mismatch error caused by the compiler. Using the following line will not help either:

intValue = (Int) byteValue

The preceding example shows that Kotlin does not support automatic type casting, so we will have to invoke it explicitly. Kotlin's library is packed with a number of useful functions, and each data type can use these functions for type conversion.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.239.44