defer-it
A compiler plugin to enable defer statements in the Kotlin programming language.
Dissimilar to Go's
defer
statements, currently, function deferral only works within a block body.
The compiler plugin transforms the (Kotlin compiler backend) IR to defer the execution of deferrable functions until the surrounding block exits.
Example
Given the following Kotlin:
fun printHelloWorld() {
defer { println("World!") }
println("Hello")
}
Ignoring the implementation details of defer
, the output of invoking printHelloWorld()
is
(reasonably) expected to be:
World!
Hello
With the defer-it-compiler-plugin
included, the body of printHelloWorld
will be
transformed (transparently during compilation) to:
fun printHelloWorld() {
try {
println("Hello")
} finally {
runCatching { println("World!") }
}
}
Thus, the output of invoking printHelloWorld()
will be:
Hello
World!
Usage
The defer-it-compiler-plugin
is enabled through the defer-it-gradle-plugin
, which is published
to Maven Central. Add
the following to the build.gradle
configuration to apply the plugin:
buildscript {
dependencies {
classpath "io.github.c-fraser:defer-it-gradle-plugin:+"
}
}
apply plugin: 'defer-it'
The gradle plugin inserts
the defer-it-api library
into the project dependencies. This library defines the defer
function, which is the only function
that the defer-it-compiler-plugin
transforms to defer the invocation of.
License
Copyright 2021 c-fraser
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Acknowledgements
Kudos to the kotlin-power-assert project which
significantly influenced the implementation of defer-it
.