try-with-resources / use / multiple resources

前端 未结 4 1812
臣服心动
臣服心动 2021-02-20 01:07

I\'m using a Java-API which heavily uses the Autoclosable-Interface and thus in Java try-with-resources. However in Java you can specify



        
4条回答
  •  悲哀的现实
    2021-02-20 01:48

    For simplicity I will use A,B and C for the chained autocloseables.

    import java.io.Closeable
    
    open class MockCloseable: Closeable {
        override fun close() = TODO("Just for compilation")
    }
    class A: MockCloseable(){
        fun makeB(): B = TODO()
    }
    class B: MockCloseable(){
        fun makeC(): C = TODO()
    
    }
    class C: MockCloseable()
    

    Using uses

    This would look like this:

    A().use {a ->
        a.makeB().use {b -> 
            b.makeC().use {c -> 
                println(c)
            }
        }
    }
    

    Making a chain use function with a wrapper

    Definition

    class ChainedCloseable(val payload: T, val parents: List) {
        fun  use(block: (T)->U): U {
            try {
                return block(payload)
            } finally {
                payload.close()
                parents.asReversed().forEach { it.close() }
            }
        }
    
        fun  convert(block: (T)->U): ChainedCloseable {
            val newPayload = block(payload)
            return ChainedCloseable(newPayload, parents + payload)
        }
    }
    
    fun  T.convert(block:(T)->U): ChainedCloseable {
        val new = block(this)
    
    }
    

    Usage

    A()
        .convert(A::makeB)
        .convert(B::makeC)
        .use { c ->
             println(c)
        }
    

    This allows you to avoid having to nest deeply, at the cost of creating wrapper objects.

提交回复
热议问题