Using extension functions to improve readability
suggest changeIn Kotlin you could write code like:
val x: Path = Paths.get("dirName").apply {
if (Files.notExists(this)) throw IllegalStateException("The important file does not exist")
}
But the use of apply is not that clear about your intent. Sometimes it is clearer to create a similar extension function to, in effect, rename the action and make it more self-evident. This should not be allowed to get out of hand, but for very common actions such as verification:
infix inline fun <T> T.verifiedBy(verifyWith: (T) -> Unit): T {
verifyWith(this)
return this
}
infix inline fun <T: Any> T.verifiedWith(verifyWith: T.() -> Unit): T {
this.verifyWith()
return this
}
You could now write the code as:
val x: Path = Paths.get("dirName") verifiedWith {
if (Files.notExists(this)) throw IllegalStateException("The important file does not exist")
}
Which now lets people know what to expect within the lambda parameter.
Note that the type parameter T for verifiedBy is the same as T : Any?, so even nullable types can use that version of the extension. verifiedWith requires a non-nullable receiver.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents