Type-casting, Type checks, and casting in Kotlin [2022]

Aditya Maurya
2 min readJan 4, 2022

Type-Casting :- It means converting one data-type to another data-type.

1. toChar() — To convert a type to Char type.

2. toInt() — To convert a type to Int type.

3. toLong() — To convert a type to Long type.

4. toFloat() — To convert a type to Float type.

5. toDouble() — To convert a type to Double type.

6. toByte() — To convert a type to Byte type.

7. toShort() — To convert a type to Short type.

8. toString() — To convert a type to String type.

NOTE:- If we want to type cast a bigger Data type to Smaller Data type then if that Big Data type is in the range of smaller data type then it get converted other wise the bigger data type get truncated and store in smaller data type.

Type-Checks and Casting:- Checking that a particular data is of the same data type which it is going to store from another variable.

Eg:- Suppose variable “a” is of string type and it gets “Any” data from a function call then it is must to check that the received data is of string type so that it can be stored in “a”.

SMART CASTS:- “is” and “!is” operator

CODE LINK: http://tiny.cc/adityaCode

So, it will print the length of the String if x is of String type other wise it will print “Not String”.

EXPLICIT TYPE-CASTING :-

A. UNSAFE CAST OPERATOR:-

CODE LINK:-http://tiny.cc/adityaCode

So, y will contain the same value as x if x is of String otherwise it will throw ERROR.

B. SAFE CAST OPERATOR:-

CODE: http://tiny.cc/adityaCode

So, y will contain the same value as x if x is of String otherwise it will store NULL.

--

--

Aditya Maurya

Software Engineer || Fitness Freak || Content Creator || Explorer