Skip to content

Instantly share code, notes, and snippets.

@ViksaaSkool
Last active December 9, 2018 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ViksaaSkool/344ffc9fe82a092b0d5ff46858cce749 to your computer and use it in GitHub Desktop.
Save ViksaaSkool/344ffc9fe82a092b0d5ff46858cce749 to your computer and use it in GitHub Desktop.
Higher-order functions
/* With */
//receives an object, and a function that will be executed as an extension function, which means that with can be used
//inside of a function to refere to the object, i.e. do something "with"
inline fun <T, R> with(receiver: T, f: T.() -> R): R = receiver.f()
//example
fun getPersonFromDeveloper(developer: Developer): Person {
return with(developer) {
Person(developerName, developerAge)
}
}
/* Apply */
//very similar to with and it's mainly used to aviod using Builders and Builder pattern - the function can initialize itself
//the way it needs and return the same object
inline fun <T> T.apply(f: T.() -> Unit): T { f(); return this }
//example
fun getDeveloper(): Developer {
return Developer().apply {
developerName = "Amit Shekhar"
developerAge = 22
}
}
/* Also */
//maybe the most intuitive of all of them - calls specified function block with the current value (this) as its argument and
//returns this value - when something additionaly needs to be done (in specified circumstances)
inline fun <T> T.also(block: (T) -> Unit): T {block(this); return this}
//example
val person: Person = getPerson().also {
print(it.name)
print(it.age)
}
/* Let */
//simple function that can be called by any object. It receives a function that will take the object as a parameter, and returns the value that this function
//returns. It is really useful to deal with nullable objects for instance. This is the definition
inline fun <T, R> T.let(f: (T) -> R): R = f(this)
//example
File("a.txt").let {
// the file is now in the variable "it"
it.delete()
}
/* Run */
//calls the specified function block and returns its result - can be with or without value as its receiver and returns its result
inline fun <R> run(block: () -> R): R {block()}
//or
inline fun <T, R> T.run(block: T.() -> R): R {block()}
//example - retrieve if person in inserted in the db in a run block
val inserted: Boolean = run {
val person: Person = getPerson()
val personDao: PersonDao = getPersonDao()
personDao.insert(person)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment