Last active
May 17, 2018 10:35
-
-
Save pablisco/89d1ce325b8d3b7ecfbd99faa2c2d367 to your computer and use it in GitHub Desktop.
Fluent Logging with Kotlin
This file contains 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
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) | |
} |
This file contains 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
// 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