美文网首页
kotlin实现defer功能

kotlin实现defer功能

作者: mihope | 来源:发表于2019-01-04 21:13 被阅读7次
    class Deferrer {
        private val actions = arrayListOf<() -> Unit>()
    
        fun defer(f: () -> Unit) {
            actions.add(f)
        }
    
        fun done() {
            actions.reverse()
            for (action in actions) {
                action()
            }
        }
    }
    
    inline fun <T> withDefers(body: Deferrer.() -> T): T {
        val deferrer = Deferrer()
        val result = deferrer.body()
        deferrer.done()
        return result
    }
    
    
    fun main(args: Array<String>) {
        withDefers {
            println("A")
            defer { println("deferred: should happen last") }
            defer { println("deferred: should happen first") }
            println("B")
        }
    }
    

    相关文章

      网友评论

          本文标题:kotlin实现defer功能

          本文链接:https://www.haomeiwen.com/subject/caxlrqtx.html