🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
In Kotlin, TypeCastException is a runtime exception that is thrown when an attempt is made to cast an object to a type with which it is not compatible. This exception is part of the Kotlin standard library and typically occurs when using the as operator incorrectly.
Table of Contents
- What is
TypeCastException? - Common Causes of
TypeCastException - Handling
TypeCastException - Examples of
TypeCastException - Real-World Use Case
- Conclusion
1. What is TypeCastException?
TypeCastException is a subclass of RuntimeException and is used to indicate that a cast to a type is not valid. This can happen when using the as operator to cast an object to a different type that it is not compatible with.
Syntax
throw TypeCastException("Exception message")
2. Common Causes of TypeCastException
- Incorrect type casting using the
asoperator. - Misusing generics.
- Casting between incompatible types.
Example
fun main() {
val obj: Any = "Kotlin"
val num: Int = obj as Int // This will cause TypeCastException
}
3. Handling TypeCastException
You can handle TypeCastException using a try-catch block to prevent your program from crashing.
Example
fun main() {
val obj: Any = "Kotlin"
try {
val num: Int = obj as Int
} catch (e: TypeCastException) {
println("Caught a type cast exception: ${e.message}")
}
}
4. Examples of TypeCastException
Example 1: Incorrect Type Casting
This example demonstrates handling incorrect type casting.
fun main() {
val obj: Any = "Kotlin"
try {
val num: Int = obj as Int
} catch (e: TypeCastException) {
println("Caught a type cast exception: ${e.message}")
}
}
Output:
Caught a type cast exception: null
Explanation:
This example catches and handles a TypeCastException caused by casting a string to an integer.
Example 2: Safe Cast Operator
This example demonstrates using the safe cast operator as? to avoid TypeCastException.
fun main() {
val obj: Any = "Kotlin"
val num: Int? = obj as? Int
println(num) // Output: null
}
Explanation:
This example uses the safe cast operator as? to perform a safe cast that returns null if the cast is not possible, avoiding TypeCastException.
Example 3: Checking Type Before Casting
This example demonstrates checking the type before casting to avoid TypeCastException.
fun main() {
val obj: Any = "Kotlin"
if (obj is Int) {
val num: Int = obj
println(num)
} else {
println("obj is not an Int")
}
}
Output:
obj is not an Int
Explanation:
This example checks the type of the object before casting to ensure that the cast is valid.
Example 4: Generics Misuse
This example demonstrates a common misuse of generics that can lead to TypeCastException.
fun <T> castToType(value: Any): T {
return value as T
}
fun main() {
try {
val str: String = castToType(123)
} catch (e: TypeCastException) {
println("Caught a type cast exception: ${e.message}")
}
}
Output:
Caught a type cast exception: null
Explanation:
This example catches and handles a TypeCastException caused by attempting to cast an integer to a string using generics.
5. Real-World Use Case: Safe Type Casting in Collections
In a real-world scenario, you might need to safely cast objects when working with collections of mixed types.
Example: Safe Type Casting in Collections
fun printNumbers(list: List<Any>) {
for (item in list) {
val num: Int? = item as? Int
if (num != null) {
println("Number: $num")
} else {
println("Not a number: $item")
}
}
}
fun main() {
val mixedList = listOf(1, "two", 3, "four", 5)
printNumbers(mixedList)
}
Output:
Number: 1
Not a number: two
Number: 3
Not a number: four
Number: 5
Explanation:
This example uses the safe cast operator as? to safely cast elements in a list to Int and prints a message if the cast is not possible, avoiding TypeCastException.
Conclusion
TypeCastException in Kotlin is a runtime exception that occurs when an attempt is made to cast an object to a type with which it is not compatible. By understanding how to handle TypeCastException using try-catch blocks, safe cast operators (as?), and type checks, you can write more robust and error-resistant code. Proper handling of type casts is crucial in real-world applications to ensure type safety and prevent runtime exceptions.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment