Extension Functions

Suppose you discover a library that does everything you need … almost. If it only had one or two additional member functions, it would solve your problem perfectly.

But it’s not your code—either you don’t have access to the source code or you don’t control it. You’d have to repeat your modifications every time a new version came out.

With Kotlin’s extension functions you can, in effect, add your own member functions to existing classes. The type you extend is called the receiver. To define an extension function, you precede the function name with the receiver type:

fun ReceiverType.extensionFunction() { ... }

End of sample. See AtomicKotlin.com for full early-access book.

Previous          Next

©2018 Mindview LLC. All Rights Reserved.