Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin 查找带有';是';操作人员_Kotlin - Fatal编程技术网

Kotlin 查找带有';是';操作人员

Kotlin 查找带有';是';操作人员,kotlin,Kotlin,我是Kotlin开发的新手,尝试创建一个函数,该函数使用异常实例和类(例如RuntimeException)来检查该实例是否是Kotlin中特定类的实例。这是因为您捕获了一种特定类型的异常。然后,您希望遍历此异常的原因,直到找到您要查找的特定异常为止 fun findExceptionType(currentException : Throwable?, exceptionToFind: KClass<Throwable>): Throwable? {

我是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
        }
fun findExceptionType(currentException:Throwable?,ExceptionFind:KClass):Throwable?{
var\u currentException=currentException
while(_currentException!!.cause==null)!!){
如果(\u currentException是exceptionToFind){
返回\u currentException.cause
}
_currentException=\u currentException.cause
}
返回空
}
其思想是,它将继续遍历
异常.cause
,直到
异常.cause
为空,或者您找到了正在搜索的异常类型。这似乎已经实现了,所以我很惊讶我不得不自己实现

使用此实用程序函数的原因是避免遍历所有的
异常。在找到所需的特定类型之前,请引发
s

更具体地说:


在Kotlin中有一个“is”操作符,例如,你可以说
if(s是String)
,但是在我上面的函数中,我想通过将
if(s是X)
之类的东西传递到函数中,使它成为通用的。
X
的类型是什么?目前我使用了
KClass
,但我不确定
操作符的类型签名是什么?

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

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

注意,您不应该使用
操作符,否则它将抛出一个
NullPointerException
。使用
?。
代替,如
\u currentException?中所述。使
执行空安全成员遍历。谢谢!我也在学习整个
?。
符号。我自己从未使用过它们,但是,如果我是对的,具体化的参数正好适用于这种情况:非常感谢。我实际上没有听说过“物化”,所以我甚至不知道如何搜索它。现在我知道了关键字,我已经找到了文档。非常感谢您的帮助:)
(x作为?字符串)?.let(::println)
,因为函数引用;-)
(x as? String)?.let { println(it) }