Are you struggling with a ClassCastException
in your Kotlin Android project? This error often occurs when you’re trying to cast an object to a type it doesn’t actually implement, which can crash your app if not handled properly. This guide will walk you through the exact steps to identify, reproduce, and fix this issue using Android Studio.

What Causes ClassCastException?
A ClassCastException
typically happens when you’re:
- Casting views from XML with the wrong type.
- Using incorrect type parameters with adapters or fragments.
- Handling objects from a generic type without checking their actual class.
Common Error Example:
val button = findViewById<TextView>(R.id.my_button) button.setOnClickListener { // This will crash because my_button is actually a Button, not a TextView }
Error Output:
java.lang.ClassCastException: android.widget.Button cannot be cast to android.widget.TextView
How to Fix It
Always make sure to use the correct type when casting objects. Use Android Studio’s “Inspect View” tool or simply check your XML.
Example: Safe View Casting
XML layout (res/layout/activity_main.xml):
<Button android:id="@+id/my_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Me" />
Kotlin activity (MainActivity.kt):
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val button = findViewById<Button>(R.id.my_button) // Correct casting button.setOnClickListener { Toast.makeText(this, "Button clicked!", Toast.LENGTH_SHORT).show() } } }
Best Practices to Avoid ClassCastException
- Always check the type of the view or object before casting.
- Use
ViewBinding
orKotlin Synthetic
to reduce manual casting errors. - Favor safe casting (
as?
) instead of force casting (as
). - Leverage generic types with proper constraints.
Example of Safe Casting:
val textView = view as? TextView textView?.text = "Safe Casting!"
Additional Learning Resource
You can also check this helpful explanation on ClassCastException in Java and Kotlin from the official Android Developer Documentation.