Skip to content

Instantly share code, notes, and snippets.

@pablisco
Last active May 17, 2018 10:35
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pablisco/89d1ce325b8d3b7ecfbd99faa2c2d367 to your computer and use it in GitHub Desktop.
Save pablisco/89d1ce325b8d3b7ecfbd99faa2c2d367 to your computer and use it in GitHub Desktop.
Fluent Logging with Kotlin
inline fun <A> A.logWith(logger: Logger, block: Logger.(A) -> Unit) : A =
this.also { logger.block(it) }
// With interface injection
interface HasLog {
val log: Logger
fun <A> A.log(block: Logger.(A) -> Unit) : A =
logWith(logger, block)
}
// manual
list.map { it.something }
.logWith(logger) { verbose("Got this $it") }
.map { "This is cool: $it" }
// injected
class MyClass(
override val log : Logger
) : HasLog {
fun dosomething(list: List<String>) : List<String> =
list.map { it.length() }
.log { verbose("Lengths are $it") }
.map { "I've got $it characters, but a new line ain't one" }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment