Instruction

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

What Are Kotlin Extension Functions?

Extension functions are a simple yet powerful concept. They add functionality to a class without modifying its source code or inheriting from it.

fun containsA(input: String): Boolean {
  return 'a' in input || 'A' in input
}
class MyString(private val value: String) {
  fun containsA(): Boolean {
    return 'a' in value || 'A' in value
  }

  override fun toString(): String {
    return value
  }
}
val myString: String
if (myString.containsA()) {
  // do something
}
fun String.containsA(): Boolean {
  return this.contains('a', ignoreCase = true)
}
val myString = "abc"
myString.containsA()

// This calls...

fun String.containsA(): Noolean {
  // In the code below, *this* refers to myString.
  return this.contains('a', ignoreCase = true)
}
class StringUtils() {
  fun containsA(input: string) {
    // Logic
  }
}

if (StringUtils.containsA(myString)) {
  // do something
}
if (myString.containsA()) {
  // do that same thing
}

What Are Kotlin Extension Properties?

Kotlin extension properties help you add new features to an existing class without making complicated changes to its structure, making your code more flexible and easier to understand.

val String.containsA: Boolean
  get() = this.contains("A", ignoreCase = true)
fun Date.toReadableString(): String {
  // Implementation to return a nicely formatted date string
}

Binding Data

RecyclerViews in Android can be a bit repetitive and cluttered in terms of code. Sometimes, you can encapsulate that repetitiveness in an extension function. Encapsulating the logic of one of these functions will make your adapters cleaner and more concise.

fun View.bindData(item: DataItem) {
  // Bind data to the view
}
fun String.isGreaterThanThreeCharacters(): Boolean = this.length > 3
fun isStringGreaterThanThreeCharacters(str: String): Boolean = str.length > 3
See forum comments
Download course materials from Github
Previous: Introduction Next: Demo