How Kotlin Extension Functions made my life easier.

How Kotlin Extension Functions made my life easier.


Kotlin is a statically typed language developed by Jetbrains,

It's used to develop mobile, desktop, and web applications.

and since Google announced in I/O 17 that Kotlin is a first class language for android development, it attracted more and more attention,

Today, I'm going to talk about one of the amazing features of Kotlin, Extension functions

Kindly note that I'm going here to talk from android perspective, but you can apply no your specific platform

as the official site says

Kotlin provides the ability to extend a class with new functionality without having to inherit from the class or use design patterns such as Decorator. This is done via special declarations called extensions. For example, you can write new functions for a class from a third-party library that you can't modify. Such functions are available for calling in the usual way as if they were methods of the original class. This mechanism is called extension functions. There are also extension properties that let you define new properties for existing classes.

Isn't this awesome!

you can add any method to any class in your project without having to extend that class, even if it was a closed library. All you have to do is to write

Class.functionName(){
  // your implementation here
}


let's take this example:

In Firebase Remote Config. I made a parameter that has an Int value, but when I wanted to get that value in my Android app, I didn't find a function to get it as int,

No alt text provided for this image
No alt text provided for this image

So I decided to add the missing function like in the following image

No alt text provided for this image

and voila :D, now I can use this function from anywhere in my project by calling

FirebaseRemoteConfig.getInt(TYPE_HERE_YOUR_PRE_DEFINED_KEY) 

You can say, okay but I could've just wrote it as

FirebaseRemoteConfig.getString("key").toInt()

I can agree with you, but, what if the operation you wanted to do was more complicated than the one above?.

let's see...

One of the most common tasks we use in android, is adding text watchers to check EditText like this:

editText.addTextChangedListener(object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
        override fun afterTextChanged(editable: Editable) {
            val text = editable.toString()
            // do what you want with the text value,
        }
    })

What If I have 10 edit texts in my screen and want to watch them or validate, what if I have more than one screen that has edit texts, well, here comes the power of extension functions:

I created a function called EditText.watchText() that takes a function as a parameter , (yes you can pass functions as a parameter in kotlin), and gives me the value of the watched text to play with :D

fun EditText.watchText(afterChanged: (text: String?) -> Unit) {
    addTextChangedListener(object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
        override fun afterTextChanged(editable: Editable) {
           
            afterChanged(editable.toString())
        }
    })
}

and call it like this

editText?.watchText{text ->    Log.i("MyTag",text) }

You see, I can call this function from anywhere in my project, it acts like if there was a function inside the EditText class called watchText() .

I would like to here from you, so let's keep in touch through:

Kotlin Egypt: Linked In | Twitter | Facebook

Ahmed Nabil: Twitter | LinkedIn


Daniel Atienza

Senior Software Engineer at Sky

4 年

How do you then remove the text watcher? I think it's a better approach using a dynamic text watcher, making also use of high order functions.

Azarudeen A.

Tech Evangelist | Cloud Native Enthusiast | Change Agent

4 年

Collection extentions are a life saver. You could add more examples on that.

?? ??? ???? , ???? ??? ?? ???? ??

要查看或添加评论,请登录

社区洞察

其他会员也浏览了