Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
    }
like image 356
HelloCW Avatar asked Nov 02 '25 20:11

HelloCW


1 Answers

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

like image 65
Jenea Vranceanu Avatar answered Nov 05 '25 16:11

Jenea Vranceanu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!