Search code examples
androidandroid-fragmentskotlinparcelablesuper

Using T in a baseFragment, will result in using that function to need a 'Nothing" instead of Fragment


This is my method:

abstract class BaseFragmentKey<T : Fragment> : Parcelable {
     fun newFragment(): T {
        val fragment = createFragment()
        val bundle = Bundle()
        bundle.putParcelable("KEY", this)
        fragment.arguments = bundle
        return fragment
    }

    protected abstract fun createFragment(): T

    @CallSuper
    open fun updateExistingFragment(fragment: T): T {
        return fragment
    }
}

But when I try to call with a Fragment:

   newFragment = newKey.updateExistingFragment(existingFragment)

It says before compiling that Type mismatch. Required Nothing, found Fragment. If I do existingFragment as Nothing it crashes cause I cannot cast to null.

How can I fix this?

enter image description here


Solution

  • The problem in wildcard in stateChange.getNewState<BaseFragmentKey<*>>. It should be for example stateChange.getNewState<BaseFragmentKey<Fragment>>