Extension functions

Kotlin provides us with extension functions. What are they? They are like an ad hoc function on top of an existing datatype/class.

For example, if we want to count the number of words in a string, the following would be a traditional function to do it:

fun countWords(text:String):Int { 
    return text.trim() 
            .split(Pattern.compile("s+")) 
            .size 
} 

We would pass a String to a function, have our logic count the words, and then we would return the value.

But don't you feel like it would always be better if there was a way that this function could be called on the String instance itself? Kotlin allows us to perform such an action.

Have a look at the following program:

fun String.countWords():Int { 
    return trim() 
            .split(Pattern.compile("s+")) 
            .size 
} 

Have a careful look at the function declaration. We declared the function as String.countWords(), not just countWords as it was previously; that means it should be called on a String instance now, just like the member functions of String class. Just like the following code:

fun main(args: Array<String>) { 
    val counts = "This is an example StringnWith multiple words".countWords() 
    println("Count Words: $counts") 
} 

You can check out the following output:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.106.7