Kotlin Extension Methods Using extension functions to improve readability


Example

In 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 as to 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 let's people know what to expect within the lambda parameter.

Note that the type parameter T for verifiedBy is same as T: Any? meaning that even nullable types will be able to use that version of the extension. Although verifiedWith requires non-nullable.