Extension functions

Often, you can encounter a situation where you wish you could add some functionality to a type that you don't own. This is what extension functions enable you to do. This is a concept where you can add members (functions and properties) to a type, outside of its definition, but still call it as a normal member. Here is one such example; we'll extend the Int type and add a function that checks if it is a power of two:

fun Int.isPowerOf2(): Boolean {
return this > 0 && ((this and this - 1) == 0)
}

The syntax of an extension function is similar to normal functions, you just add the type that you are extending followed by the dot before the function name.

We can call the function now as a normal member:

val n = 8
val isPowerOf2 = n.isPowerOf2()

Inside the extension function, this keyword refers to the instance of the type we've extended. In our example, this keyword inside the extension function would refer to number eight.

Note that inside the extension function, you cannot access private members of the type you are extending.

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

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