In Dart, the "
is
" and "
as
" keywords are used for type checks and type casts, respectively.
1. "is" keyword : The "
is
" keyword is used for type checks to determine if an object is of a specific type. It returns a boolean value, true or false, based on the object's type. It is commonly used in conditional statements or to perform type-specific operations.
Example :
var obj = 'Hello';
if (obj is String) {
print('The object is a String.');
} else {
print('The object is not a String.');
}​
In the above example, the "
is
" keyword is used to check if the variable `
obj
` is of type String. If it is, the message "
The object is a String." will be printed; otherwise, the message "The object is not a String." will be printed.
2. "as" keyword : The "
as
" keyword is used for type casts, allowing you to explicitly cast an object to a specific type. It performs a type check at runtime and casts the object to the desired type if the check is successful. If the object cannot be cast to the specified type, a runtime exception may occur.
Example :
var obj = 'Hello';
var str = obj as String;
print(str.toUpperCase());​
In the above example, the "
as
" keyword is used to cast the variable `
obj
` to the String type and assign it to the variable `
str
`. Since `
obj
` is already a String, the cast is successful, and the `
toUpperCase()
` method can be called on `
str
`.
It's important to note that if the object is not of the specified type, a runtime exception, such as a `
TypeError
`, may occur. Therefore, it is recommended to use the "
is
" keyword to perform a type check before using the
"as
" keyword for type casting to ensure safety.
Both "
is
" and "
as
" keywords are useful when dealing with polymorphism, conditional branching based on object types, and when you need to perform specific operations based on an object's type in Dart.