Skip to content

Instantly share code, notes, and snippets.

@pksokolowski
Created March 14, 2019 17:44
Show Gist options
  • Save pksokolowski/9b1dbe23b88e9434794f472a1fc49a7f to your computer and use it in GitHub Desktop.
Save pksokolowski/9b1dbe23b88e9434794f472a1fc49a7f to your computer and use it in GitHub Desktop.
Adding a language-feature-like functionality in Kotlin and Lisp for comparison. Using a simplified "using" statement as an example.
// some setup
interface IDisposable {
fun dispose()
}
data class Handle(val resource: String) : IDisposable {
override fun dispose() {
println("Disposing of $this")
}
}
// the actual using's definition
inline fun <T : IDisposable> using(disposable: T, block: T.() -> Unit) = disposable.apply(block).dispose()
// usage
fun main() {
using(Handle("fancy name")) {
println("executing the code provided in using statement.. $resource")
}
}
; some setup
(defclass handle()
((resource :initarg :resource)))
(defmethod dispose ((obj handle))
(format t "~%Disposing of ~a"
(slot-value obj 'resource))
nil)
; the actual using's definition
(defmacro using (var form &body body)
`(let ((,var ,form))
(unwind-protect (progn ,@body)
(dispose ,var))))
; usage
(using x (make-instance 'handle :resource "fancy name")
(format t "~%Executing code block while using: ~a"
(slot-value x 'resource)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment