is and !is Operators
In Kotlin, you can use the is and !is operators to check if a object is a specific type. This will automatically cast the object to the type it is checking, also known as Smart Cast.
Syntax for is
In the example, there is a function call castExample that accepts a value of any type.
This will print 1001 ("100" + 1) since x is casted to a String using the is operator.
This will print 101 (100 + 1) since x is casted to a Int.
Kotlin also provides ways to forcefully cast a type to an object using the "as" operator.
Syntax for as
In the example, we are using the as operator to forcefully turn a String into a integer. However, this will throw an exception during runtime since a String cannot be turned into an Integer.
Unsafe and Safe Casts
Using the as operator forcefully cast an object to another type. This is also known as Unsafe casting.
To turn the Unsafe cast to a safe one, we will need to use the Safe Cast operator "as?" (as with the ?).
The as? operator will attempt to make the cast. If the cast operation fails, it will return null and no exception will be thrown.
©2019 - 2023 Codeible. All rights reserved.