Kotlin`by`关键字对可为空的委托有效吗?

时间:2019-03-26 13:39:25

标签: android kotlin delegation

我对Kotlin编译器的功能特别是table.foo { border: 1px solid red }感到非常兴奋-它节省了生成胶化代码的时间:

https://kotlinlang.org/docs/reference/delegation.html

但是我希望委托为空,并委托代码首先检查它是否为null,然后返回是否为

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

编译^时,我得到by

Kotlin是否仍然可行?

更详细地说,我希望Kotlin编译器生成对https://developer.android.com/reference/android/webkit/WebChromeClient中的包装的impl(interface Base { val message: String fun print() } class BaseImpl(val x: Int?) : Base { override val message = "BaseImpl: x = $x" override fun print() { println(message) } } class Derived(b: Base?) : Base by b { // This property is not accessed from b's implementation of `print` override val message = "Message of Derived" } fun main() { val b = BaseImpl(10) val derived = Derived(b) derived.print() println(derived.message) } )的转发调用,如下所示:

Type mismatch: inferred type is Base? but Base was expected

1 个答案:

答案 0 :(得分:1)

您可以使用dynamic proxies自己制作,尽管我并不推荐这么做。请注意,对于非void方法,无法要求覆盖它们。下面的实现只是无条件地为它们引发异常,但是您仍然可以将它们称为非空x

inline fun <reified T : Any> nullableProxy(x: T?): T {
    val handler = InvocationHandler { _, method, args ->
        if (method.returnType == Void.TYPE) {
            if (x != null) {
                method.invoke(x, *(args ?: arrayOf()))
            }
        } else 
            throw UnsupportedOperationException("Non-void method")
    }

    return Proxy.newProxyInstance(
        T::class.java.classLoader,
        arrayOf(T::class.java),
        handler) as T
}

class Derived(b: Base?) : Base by nullableProxy(b)

这也不会像直接实现方法那样好。