首页 > 解决方案 > 使用“is”运算符查找类实例的通用方法

问题描述

我是 Kotlin 开发的新手,并试图创建一个函数,该函数接受一个异常实例和一个类(例如 RuntimeException)来检查该实例是否是 Kotlin 中特定类的实例。这个想法是您已经捕获了特定类型的异常。然后,您想要遍历此异常的原因,直到您找到您正在寻找的特定异常。

        fun findExceptionType(currentException : Throwable?, exceptionToFind: KClass<Throwable>): Throwable? {
            var _currentException = currentException
            while((_currentException!!.cause == null)!!) {
                if (_currentException is exceptionToFind) {
                    return _currentException.cause
                }
                _currentException = _currentException.cause
            }
            return null
        }

这个想法是它将继续遍历exception.cause直到exception.cause为空,或者您找到了您正在搜索的异常类型。这似乎已经实现了,所以我很惊讶我不得不自己实现它。

这个效用函数的原因是避免必须遍历所有exception.causes 直到找到所需的特定类型。

更加具体:

在 Kotlin 中有一个 'is' 运算符,例如你可以说if (s is String),但是在我上面的函数中,我想通过将if (s is X)whereX传递给函数来使其具有通用性。的类型是X什么?目前我已经使用KClass但我不确定is操作符的类型签名是什么?

标签: kotlin

解决方案


我同意@dyukha。reified在这里使用类型参数非常方便。有了它,您可以重写您的函数,例如:

inline fun <reified T : Throwable> findExceptionType(throwable: Throwable?): T? {
    var error = throwable
    while (error !is T) {
        error = error?.cause
    }
    return error
}

作为通用if (s is X) where X is passed into the function的,你可以使用这样的东西:

(x as? String)?.let { println(it) }

推荐阅读