Kotlin - 当表达式超过类类型时

fri*_*ice 2 kotlin

我正在尝试编写一个调用处理程序,它使用映射(在运行时提供)来实现接口的 getter。

这非常粗糙。我知道可能返回的基本类型,所以我可以使用when 表达式。

我还没有找到一种方法来避免使用类名作为when表达式的主题;有没有更好的办法?

class DynamicInvocationHandler<T>(private val delegate: Map<String, Any>, clzz: Class<T>) : InvocationHandler {

    val introspector = Introspector.getBeanInfo(clzz)
    val getters = introspector.propertyDescriptors.map { it.readMethod }

    override fun invoke(proxy: Any, method: Method, args: Array<Any>?): Any? {
        if (method in getters) {
            // get the value from the map
            val representation = delegate[method.name.substring(3).toLowerCase()]
            // TODO need better than name
            when (method.returnType.kotlin.simpleName) {                
                LocalDate::class.simpleName -> {
                    val result = representation as ArrayList<Int>
                    return LocalDate.of(result[0], result[1], result[2])
                }
                // TODO a few other basic types like LocalDateTime
                // primitives come as they are
                else -> return representation
            }
        }
        return null
    }
}
Run Code Online (Sandbox Code Playgroud)

Oma*_*gra 10

您可以在语句中使用类型而不是类名when。类型匹配后,Kotlin 智能转换会自动转换它

例子

val temporal: Any? = LocalDateTime.now()

when (temporal){
    is LocalDate -> println("dayOfMonth: ${temporal.dayOfMonth}")
    is LocalTime -> println("second: ${temporal.second}")
    is LocalDateTime -> println("dayOfMonth: ${temporal.dayOfMonth}, second: ${temporal.second}")
}
Run Code Online (Sandbox Code Playgroud)


Moi*_*ira 6

when表达式支持任何类型(与 Java 不同switch),因此您可以只使用KClass实例本身:

when (method.returnType.kotlin) {                
    LocalDate::class -> {
        ...
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)