August 2018
Beginner
178 pages
4h 56m
English
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 = 8val isPowerOf2 ...
Read now
Unlock full access