Type Checking and Casting
Checking Types with is
The is operator checks whether a value is an instance of a given type at runtime, returning true or false, similar to instanceof in Java.
Example: Checking Types with is
fun describe(value: Any) {
if (value is String) {
println("It is a String of length ${value.length}")
} else {
println("Not a String")
}
}
fun main() {
describe("Kotlin")
describe(42)
}
Login to try C/C++/Java/PHP code in the editor
Smart Casts
Once an is check confirms a value's type, Kotlin automatically treats it as that type for the rest of that scope -- no manual cast is needed, which is called a smart cast.
Example: Smart Casts
fun printLength(value: Any) {
if (value is String) {
// value is smart-cast to String here
println("Length: ${value.length}")
}
}
fun main() {
printLength("Hello")
}
Login to try C/C++/Java/PHP code in the editor
Unsafe Cast with as
The as operator forcibly casts a value to a given type, throwing a ClassCastException at runtime if the value is not actually compatible with that type.
Note: Only use as when you are certain of the type; otherwise prefer as?.
Example: Unsafe Cast with as
fun main() {
val value: Any = "Kotlin"
val text = value as String
println("Cast succeeded: $text")
}
Login to try C/C++/Java/PHP code in the editor
Safe Cast with as?
The as? operator attempts the same cast but returns null instead of throwing when it fails, which is much safer when the type is uncertain.
Example: Safe Cast with as?
fun main() {
val value: Any = 42
val text = value as? String
println("Safe cast result: $text")
}
Login to try C/C++/Java/PHP code in the editor
- Using the unsafe cast
ason a value that might not actually be that type, causing aClassCastExceptionat runtime. - Not using smart casting after an
ischeck, and casting manually anyway, producing more verbose code than necessary. - Forgetting that
as?returnsnullinstead of throwing, and not handling thatnullresult.
ischecks whether a value is a certain type at runtime, returning aBoolean.- Kotlin's smart casts automatically treat a value as the checked type inside an
if (x is Type)block, without a manual cast. asperforms an unsafe cast that throwsClassCastExceptionif the value is not actually that type.as?performs a safe cast that returnsnullinstead of throwing when the cast is not possible.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: