Search code examples
androidkotlinkotlin-extension

How can I optimize code for extension function of Context, Fragment and Activity in Kotlin?


The Code A is extension function for Context, Fragment and Activity.

I think it's redundant, how can I optimize it?

Code A

    fun Context.toast(msg: String){
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
    }
    
    fun Context.toast(@StringRes resId: Int){
        toast(getString(resId))
    }
    
    fun Context.toast(@StringRes resId: Int,msg: String){
        toast(getString(resId) + msg)
    }
    
    fun Context.toast(msg: String,@StringRes resId: Int){
        toast(msg + getString(resId))
    }
    
    //------------------------------------------------

    fun Fragment.toast(msg:String) {
        requireContext().toast(msg)
    }
    
    fun Fragment.toast(@StringRes resId: Int) {
        toast(requireContext().getString(resId))
    }
    
    fun Fragment.toast(@StringRes resId: Int, msg: String) {
        toast(requireContext().getString(resId) + msg)
    }
    
    fun Fragment.toast( msg: String, @StringRes resId: Int) {
        toast(msg+ requireContext().getString(resId))
    }
    
    //------------------------------------------------

    fun Activity.toast(msg: String){
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
    }
    
    fun Activity.toast(@StringRes resId: Int){
        toast(getString(resId))
    }
    
    fun Activity.toast(@StringRes resId: Int,msg: String){
        toast(getString(resId) + msg)
    }
    
    fun Activity.toast(msg: String,@StringRes resId: Int){
        toast(msg + getString(resId))
    }

Solution

  • Context extension functions should be enough. You will be able to use it virtually in any place where a UI component is available.

    We can remove extensions for Activity because Activity is an indirect subclass of Context class.

    And we also can remove Fragment extensions because they are not useful until a fragment is attached to an activity (which is the context).

    fun Context.toast(msg: String){
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
    }
    
    fun Context.toast(@StringRes resId: Int){
        toast(getString(resId))
    }
    
    fun Context.toast(@StringRes resId: Int,msg: String){
        toast(getString(resId) + msg)
    }
    
    fun Context.toast(msg: String,@StringRes resId: Int){
        toast(msg + getString(resId))
    }
    

    These functions can be used in an activity:

    Use of extension functions in Activity

    And in a fragment. It is logically correct and intentional that we must first get a reference to a Context:

    Use of extension functions in Fragment