Kotlin type Checks and Casts: 'is' and 'as'

In this article, we will learn how to apply checks for a particular data type, smart cast, safe and unsafe cast operators?
Submitted by Aman Gautam, on January 21, 2018

Type check: 'is' and '!is' operator

is operator is used to check whether an object is associated to a particular data type or not. This is useful when we haven’t any idea that which type of data is coming from the source. By using is operator we can confirm the type of data or object and then work accordingly on it.

It takes two arguments in the form of: a is b

Where, a is the object and b is the type. This will return true if a is of b type.

Example:

if(str is String) {
	return str.length
}

There is another operator !is which works as opposition to the is operator.

if(str !is String){
	print("Not a string")
}

Smart casts

Smart cast is a technique in which kotlin compiler automatically (safe) cast the objects to their respective type by tracking the is checks and explicit cast to immutable values.

fun getStrLength(str: Any):Int?{
	if(stris String) {
		//automatically cast to string type.
		return str.length 
	}
	return null
}

Smart cast can be used in when expressions and while loop.

fun get(x: Any):Any?{
	return when(x){
		is Int -> (x+10)
		is Double -> (x/10)
		is String ->x.length
		else ->null;
	}
}
print(get("ABC"))	//output : 3
print(get(11))		// output : 12

Smart cast doesn’t work when the compiler doesn’tguaranteethat the variable can’t change between the check and the usage. More specifically, smart casts are applicable according to the following rules:

  1. val local variables - always;
  2. val properties - if the property is private or internal or the check is performed in the same module where the property is declared. Smart casts aren’t applicable to open properties or properties that have custom getters;
  3. var local variables - if the variable is not modified between the check and the usage and is not captured in a lambda that modifies it;
  4. var properties - never (because the variable can be modified at any time by other code).

Explicit Casting

1) Unsafe cast operator

We can use as operator to explicitly cast a variable to a target type.

var s= str as String

This is called unsafe because it can through ClassCastException if casting is not possible.

var str = 123
// throws  ClassCastException
var s = str as String

If we are trying to cast nullable variable to a to a type, then the target type must be of nullable type.

var str : Any ? = null
var s = str as String?
print(s)  //print null

2) Safe Cast operator

As sometimes when casting is not possible the compiler throws ClassCastException. To prevent the exception, we can use safe cast operator (as?), which instead of throwing any exception just return null.

Example 1:

var str:Any?=1998
var s = str as String?
print(s)

This will throw ClassCastException.

Example 2:

var str:Any?=1998
var s= str as? String?
print(s)

This code will run and print null instead of throwing exception.




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.