3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

kotlinでdefer的なことをする

Posted at

kotlinで、他の言語のdeferのようなことを実現するコード。

import java.lang.Exception

class MyDefer {

    val list = ArrayList<() -> Unit>()

    fun defer(fn: () -> Unit) {
        list.add(fn)
    }

    fun doDefer() {
        list.reversed().forEach {
            try {
                it()
            } catch(_: Exception) {
            }
        }

    }
}

fun mydefer(fn: MyDefer.() -> Unit ): MyDefer {
    val mydefer = MyDefer()
    try {
        mydefer.fn()
    } finally {
        mydefer.doDefer()
    }
    return mydefer
}


fun main() {

    mydefer {
        print("1\n")
        defer{ print("defer1\n") }
        defer{ print("defer2\n") }
        print("2\n")
    }
}

書いてはみたが、きっと使わない気がする。

3
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?