Kotlin – Extension Functions


What is Extension Functions?

Kotlin, provides the ability to extend a class with a new functionality without having to inherit from the class or use any type of design pattern such as Decorator (Annotation in Java).

What it looks like?

We want to add sayHello function to all String objects in our project. We can do it by Inheritance and Extension Function.

Inheritance: We should inherit from String class and add sayHello function to it then we should use our new custom String class instead of original String class.

class CustomString : String{
   fun sayHello(): String {
      return "Hello ".plus(this)

// usage
val myString: CustomString = "Hani";

// output: Hello Hani

Extension Function: MAGIC IS HERE, below function can do it for us 🙂

fun String.sayHello(): String {
   return "Hello ".plus(this)

// usage
val myString = "Hani"

// output: Hello Hani

Some Useful Examples

Hiding soft keyboard in Android

fun Activity.hideKeyboard() {
   val view = this.currentFocus
   if (view != null) {
      val imm = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view.windowToken, 0)

// usage

Convert DP to PX

fun Context.convertDpToPx(dps: Float): Int = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dps, resources.displayMetrics).toInt()

// usage:

Trim text of EditText

fun EditText.trim(): String = this.text.toString().trim()

// usage

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.