Created
October 15, 2014 23:39
-
-
Save g0t4/01a49114553c9fe0d0d8 to your computer and use it in GitHub Desktop.
A ruby like tap method for kotlin, except for any type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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