Skip to content

Instantly share code, notes, and snippets.

@senamit2708
Last active August 11, 2023 13:13
Show Gist options
  • Save senamit2708/241def266ff724e13489052f17457afe to your computer and use it in GitHub Desktop.
Save senamit2708/241def266ff724e13489052f17457afe to your computer and use it in GitHub Desktop.
extension function
Extension functions in Kotlin allow you to natively implement the "decorator" pattern. For example,
they allow you to write new functions for a class from a third-party library that you can't modify.
Such functions can be called in the usual way as if they were methods of the original class.
https://hackernoon.com/using-kotlin-extension-functions-the-good-the-bad-and-the-ugly
https://github.com/agustarc/Android-Kotlin-Extensions/blob/master/android-view/src/main/java/github/agustarc/android/extensions/view/ViewExt.kt
https://github.com/senamit2708/Android-Kotlin-Extensions
private fun saveUserDetailToDB() {
val name = binding.txtName.text.toString()
var mobNo = binding.txtMobNo.text.toString()
mobNo = mobNo.addMobileExtension() //extension function
var user = User(name = name, mobileNumber = mobNo)
user = user.firstLetterCapital() //extension function
userViewModel.saveUserDetail(user)
}
package com.example.coroutinelearning
import android.view.View
import com.example.coroutinelearning.entity.User
public fun User.firstLetterCapital(): User {
val name = this.name.uppercase()
return User(name = name, mobileNumber = this.mobileNumber)
}
public fun String.addMobileExtension(): String {
return "+91- $this"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment