Search code examples
androidkotlinkotlin-extension

Name conflicts when using Method extension and Inheritance


I have an extension

fun Fragment.showToast(message: String, toastLength: Int = Toast.LENGTH_SHORT) {
    Toast.makeText(context, message, toastLength).show()
}

In project we're using MVP:

interface MyContract {
    interface View {
        fun showToast(message: String)
    }
}

class MyFragment : Fragment(), MyContract.View {
    override fun showToast(message: String) {
        showToast(message)
    }
}

So in MyFragment.showToast(message) I expect to call extension function instead of StackOverflowException.

Is it possible to call extension function directly? Something like:

Fragment.showToast(this, message)

or I just need to give another name?


Solution

  • You could cast your MyFragment class to Fragment and do:

    class MyFragment : Fragment(), MyContract.View {
        override fun showToast(message: String) {
            val fragment = this as Fragment
            fragment.showToast(message)
        }
    }
    

    This way you will refer to the extension function of the Fragment class