Skip to content

Instantly share code, notes, and snippets.

@pablisco
Last active May 17, 2018
Embed
What would you like to do?
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