From the course: Android Development Tips

Unlock this course with a free trial

Join today to access over 22,600 courses taught by industry experts.

Create Kotlin extension functions

Create Kotlin extension functions - Android Tutorial

From the course: Android Development Tips

Create Kotlin extension functions

- [Instructor] Kotlin allows you to define and add functions to existing classes. These are called extension functions and they're a great way to encapsulate boilerplate code that otherwise might have to be repeated many times. You can define extension functions anywhere, including in independent files. I'll go to my base package in this project and I'll create a new Kotlin file that I'll name Extensions, and I won't turn it into a class. Now, to declare a function, I'll use the keyword fun and then I'll start with the class that I'm adding the function to. I'm going to add this to the view class from android.view. Now, I can name my function and I'll call it flipVisibility. The goal of this function is to examine the current visibility setting for a view that is a visual widget and then change it. So, if it's visible, I'll make it invisible, and if it's invisible, I'll make it visible. I'll use some simple conditional logic. I'll say if this.visibility equals the constant…

Contents