

We can add operators to our classes by using the operator keyword and we can create infix functions with the infix keyword. There are a few other keywords that can be attached to our extension functions. Println(twentySeventeen.isItSunny()) // :( Var twentySeventeen = Summer("Ireland", true) data class Summer(var country: String, var sunny: Boolean)Ĭountry = "Ireland" -> "Hah, nope. We can also access the internals of our classes with these extensions, the same way we could with standard member functions.

That String extension defined above is an example of the simplest use. With this neat little functionality we can extend classes from libraries with all the needed functionality and make wishy-washy collections of static Now that that extension is defined, it is available to be imported throughout the project. In the example above, we have created an extension function to String class. Println("What's up".uberized()) // What's up, bro fun String.uberized(): String = this + ", bro" In Kotlin, extensions make those classes disappear. Sometimes in Java codebase you might see a bunch of classes ending with the Util or Utils keyword. Extensions are a brilliant way to bring in extra functionality in a nicely context-bound way. Kotlin language has the capability to extend any object with functions or properties, even if you don't have access to modify the codebase of that particular class. So, we have been throwing around the term “extension function” in a few places. Finally, we'll wrap up this series with a short intro on visibility and packages. Today we'll see more extension function magic and talk a little about generics and delegates. Check out Part 1 and Part 2 if you've missed them. We also touched on a few extension functions from the standard library. In the last few articles, we went through Kotlin syntax basics, lambdas, null and type safety.
