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
[variable] is [type]
Example
In the example, there is a function call castExample that accepts a value of any type.
castExample("100")
This will print 1001 ("100" + 1) since x is casted to a String using the is operator.
castExample(100)
This will print 101 (100 + 1) since x is casted to a Int.
as Operator
Kotlin also provides ways to forcefully cast a type to an object using the "as" operator.
Syntax for as
[variable] as [type]
Example
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 ?).
var number = str as? Int
The as? operator will attempt to make the cast. If the cast operation fails, it will return null and no exception will be thrown.