DEV Community

Discussion on: Kotlin: What are your favorite extension functions that you authored?

 
anoop44 profile image
Anoop S S

There is no such limitation documented anywhere, you can add new functionality to any class even if it is not related, is because it is not possible to figure out whether functionality belong to the class or not. Consider how you use the extension function to understand what I was trying to say. Say you added a method show toast to String class.

fun String.showToast(context: Context){
     Toast.makeText(context, this, LENGTH_SHORT).show()
}

When you call it from any class it will be something like this

val name = user.name
name.showToast(context)

It has become like name.length() or name.isEmpty(). But the added methods should not be really part of String class. Look at the extensions provided by android-ktx library. It can be found that those extensions belong to specific classes and and are not very generic utility methods