Reputation: 23
I'm learning to code in Android with Kotlin, and have issues when casting between classes.
So I had these classes defined:
abstract class ListFragment : Fragment()
class NewListFragment : ListFragment()
and when I tried to use it when implementing a function that returns a Fragment, it throws ClassCastException. There was IDE warning about the failing cast too
override fun getItem(position: Int): Fragment {
return when(position){
0 -> NewListFragment() as Fragment
I don't know where I got wrong
Upvotes: 0
Views: 132
Reputation: 14887
Are you using the same Fragment
class?
android.app.Fragment
(deprecated as of Android P)android.support.v4.app.Fragment
You seem to be casting to android.support.v4.app.Fragment
, judging from the exception message. Are your imports in that file incorrect?
The warning in IntelliJ about an impossible cast only appears when it is truly impossible to cast to that specific type (that is, when their type hierarchies are completely different), which is why I think that this is likely the problem.
Additionally, you don't need to cast to a supertype. Such a conversion is already inferred, so you can remove the cast.
Upvotes: 4