Created
March 14, 2019 17:44
-
-
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.
This file contains hidden or 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
// 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") | |
} | |
} |
This file contains hidden or 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
; 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