2

The Closeable interface in Java provides a convenient abstraction that facilitates the management of resources that can be closed. In the context of multi-platform kotlin, is there a pattern, practice or feature that can help breach the gap between a shared/multi-platform Closeable interface and the actual Java Closeable interface knowing that these are necessarily two different types?

The effects of not being able to close the type difference and/or having a standard-lib closeable are the proliferation of Closeable interfaces that can't be combined across libraries even though they are fundamentally the same thing.

4

1 回答 1

4

这已经在 Kotlin 团队的 kotlinx-io 库中为您完成了。

https://github.com/Kotlin/kotlinx-io

因为Closeable您应该直接使用该库,无需创建自己的库。


但是,如果您想创建自己的类似跨平台抽象,这是一个很好的示例。这是它在封面下所做的事情......

实际执行关闭逻辑的通用实现,只期望每个平台都有可用的接口:(来源)

expect interface Closeable {
    fun close()
}

inline fun <C : Closeable, R> C.use(block: (C) -> R): R {
    try {
        val result = block(this)
        close()
        return result
    } catch (first: Throwable) {
        try {
            close()
        } catch (second: Throwable) {
            first.addSuppressedInternal(second)
        }
        throw first
    }
}

@PublishedApi
internal expect fun Throwable.addSuppressedInternal(other: Throwable)

JVM 版本只是一个简单的类型别名,它与预期的接口相匹配,意味着它与现有代码兼容,以及抑制内部异常的实现。(资源)

actual typealias Closeable = java.io.Closeable

@PublishedApi
internal actual fun Throwable.addSuppressedInternal(other: Throwable) {
    AddSuppressedMethod?.invoke(this, other)
}

private val AddSuppressedMethod: Method? by lazy {
    try {
        Throwable::class.java.getMethod("addSuppressed", Throwable::class.java)
    } catch (t: Throwable) {
        null
    }
}

并且JS 版本是一个新的接口:(来源)

actual interface Closeable {
    actual fun close()
}

@PublishedApi
internal actual fun Throwable.addSuppressedInternal(other: Throwable) {
}

对于native 它类似于 JS,等等每个平台......

于 2018-11-17T22:24:29.417 回答