Skip to content

Instantly share code, notes, and snippets.

@g0t4
Created October 15, 2014 23:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save g0t4/01a49114553c9fe0d0d8 to your computer and use it in GitHub Desktop.
Save g0t4/01a49114553c9fe0d0d8 to your computer and use it in GitHub Desktop.
A ruby like tap method for kotlin, except for any type
/**
* Provide a means to fluently tap into a chain of method calls so as not to need to declare unnecessary variables
* */
public fun <T : Any, R> T.tap(tap: (T) -> R): T {
tap(this)
return this
}
// here's an example where I'm in a fluent builder and I'd like to log the URI of the request without introducing a variable
val response = this.builds.queryParam("locator", "buildType:{buildTypeId},count:1,personal:false,canceled:false")
?.resolveTemplate("buildTypeId", buildTypeId)
?.tap { logger.message("Requesting last finished build ${it?.getUri()}") }
?.request()
?.get(javaClass<Builds>());
// much like let from https://github.com/JetBrains/kotlin/blob/b20b406d8e42f2a6eae708efcf40b25e8771e98e/libraries/stdlib/src/kotlin/Standard.kt
public inline fun <T : Any, R> T.let(f: (T) -> R): R = f(this)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment