As vs Is in Kotlin

Learn via video courses
Topics Covered

The article delves into the distinctions between as vs is in Kotlin, shedding light on their crucial roles in type-checking and casting. Both keywords are integral to Kotlin's type system and they serve distinct purposes. The is keyword is primarily used for type checking, ensuring that an object conforms to a specified type at runtime. On the other hand, the as keyword is utilized for explicit type casting, enabling developers to convert objects from one type to another when certain conditions are met. Understanding the subtle differences between as vs is in Kotlin is essential for writing robust and type-safe Kotlin code. The article provides insightful examples and practical scenarios to explain the diverse usage of as vs is in Kotlin programming.

Type Check and Casts in Kotlin

In Kotlin, type checks and casts are mechanisms used to work with different data types, ensuring type safety and allowing developers to handle variables of different types flexibly. Let's break down the concepts of type checks and casts in Kotlin:

Type Check:

  • The is operator is used in Kotlin to perform a type check. It checks whether an expression is an instance of a particular type.

Casts:

Casting is the process of converting a variable from one type to another. In Kotlin, casting can be done using the as operator.

There are two types of casts:

  • Safe Cast (as?): It returns null if the cast is not possible.
  • Unsafe Cast (as): It throws a ClassCastException if the cast is not possible.

Using type checks and casts in Kotlin helps ensure that your code is type-safe, reducing the risk of runtime errors related to incorrect data types.

is and !is Operation in Kotlin

In Kotlin, the is and !is operators are used for type checking, allowing you to check if an object is an instance of a particular type or is not an instance of a particular type, respectively. Let us look at both of them one by one.

is Operator:

Usage: Checks if the expression on the left side is an instance of the specified type on the right side.

Syntax:

Let us look at the following example to understand this better.

Code:

Output:

Explanation: In the example, the is operator checks if value is a String, and if true, it executes the corresponding block.

!is Operator:

Usage: Checks if the expression on the left side is not an instance of the specified type on the right side.

Syntax:

Let us look at the following example to understand this better.

Code:

Output:

Explanation: In this example, the !is operator checks if value is not a String, and if true, it executes the corresponding block.

Smart Casting in Kotlin

In Kotlin, smart casting is a feature that allows the automatic casting of a variable to a more specific type within a certain scope when its type has been checked. This feature eliminates the need for explicit casting in some situations, making the code more concise and readable. Smart casting is available for local variables and properties that are checked using the is operator.

Here's how smart casting works:

Local Variables:

Code:

Output:

Explanation:

In this example, within the if block, the compiler automatically smart casts value to String, allowing you to access the length property without the need for explicit casting.

Properties:

Code:

Output:

Explanation:

In this case, the smart casting works for the myProperty within the if block, casting it to String when the type check succeeds.

It is important to note that smart casts don’t work when the compiler can’t guarantee that the variable can’t change between the check and the usage.

Smart casts are subject to the following rules:

  • For val local variables, smart casts are always applicable.
  • For val properties, smart casts are applicable if the property is private or internal, or if the check is performed in the same module where the property is declared. However, smart casts aren't applicable to open properties or properties with custom getters.
  • For var local variables, smart casts are applicable if the variable remains unmodified between the check and its usage and is not captured in a lambda that modifies it.
  • For var properties, smart casts are never applicable since the variable can be modified at any time by other code.

Explicit Cast Operator as in Kotlin

In Kotlin, the explicit cast operator is denoted by the as keyword. It is used to explicitly cast a variable or expression from one type to another. The syntax for the explicit cast is as follows.

Here, expression is the value you want to cast, and Type is the target type you want to cast to.

Code:

Output:

Explanation:

In this example, myVariable is of type Any, but because we know it contains a String (due to the initialization), we can use the as operator to explicitly cast it to a String. After the cast, we can access the length property of the String.

It's important to note that if the cast is not possible, a ClassCastException will be thrown at runtime. To handle potential casting issues, you can use the safe cast operator as?, which returns null if the cast is not possible instead of throwing an exception.

Examples of is and as Operator in Kotlin

Let's look at the following example.

Code:

Output:

Explanation:

  • We have a Person class representing a person with a name and age.
  • We have an Animal class as a base class for animals and a Cat subclass of Animal with an additional property for color.
  • The is operator is used for type checking, ensuring that the objects are instances of the expected classes.
  • The as operator is used for explicit casting, allowing us to cast an object to a specific type if it is appropriate, and it returns null if the cast is not possible (using the safe cast as?).

Difference Between is and as Operator in kotlin

The table below shows is vs as in Kotlin.

Featureis Operatoras Operator
PurposeType checkingExplicit casting
Syntaxexpression is Typeexpression as Type
UsagePrimarily used in if statements or when expressions for type checksUsed for explicit casting when you are confident about the type
Handling TypesWorks with both nullable and non-nullable typesWorks with non-nullable types (use as? for safe cast)
Error HandlingDoes not throw an exception; safe for all typesMay throw a ClassCastException if the cast is not possible

Conclusion

Here are the key conclusions of this article on as vs is in kotlin:

  • is operator is used for type checking to determine if an expression is an instance of a particular type. Syntax: expression is Type.
  • as operator is used for explicit casting, converting an expression from one type to another. Syntax: expression as Type.
  • is operator is safe for all types while as operator may throw ClassCastException; use with caution, especially with non-nullable types.
  • is operator is ideal for conditional logic, ensuring safe type handling. You can prefer as? opeartor for safe casting to prevent runtime exceptions.
  • is operator enables smart casting, narrowing the type within a specific scope. For as operator, smart casting is not applicable with var properties due to potential modifications.