Learning about extensions

Kotlin has introduced ways to have custom functionality in existing code without subclassing or writing design patterns over it such as decorator patterns. The following method in String to count the number of the simple letter A can be written without ever subclassing:

fun String.countAs() : Int {
var count = 0;
for(i in 0..(this.length - 1)) {
if (this.get(i) == 'a') {
count++;
}
}

    return count;
}

It can also be used as follows:

println("aaaaabcdefghijkl".countAs());
..................Content has been hidden....................

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