kotlin - 使用“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.cause
s 直到找到所需的特定类型。
更加具体:
在 Kotlin 中有一个 'is' 运算符,例如你可以说if (s is String)
,但是在我上面的函数中,我想通过将if (s is X)
whereX
传递给函数来使其具有通用性。的类型是X
什么?目前我已经使用KClass
但我不确定is
操作符的类型签名是什么?
解决方案
我同意@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) }
推荐阅读
- python - 需要一个类似字节的对象,而不是 numpy.frombuffer 中的“str”
- firebase - Nuxt.js & Firebase.services.analytics 原因
为空白且没有错误 - flutter - GetX 微服务与 FloatingActionButton + 有什么好的选择?GetX 还是 Flutter BLoC?
- python - 按钮必须在其中一个模板中有工具提示,但不能在其他模板中
- java - 添加事件处理代码后没有main方法错误
- php - 如何基于 CPT Wordpress 为标签创建自定义模板
- imodeljs - 如何将两个 imodel 合并为一个(使用 IModelTransformer)
- datetime - SSRS 创建以 15 分钟间隔更新的临时日期时间表 - 参数未显示
- php - 如何在基于 Apple Silicon M1 的 PHP 版本(php@7.4)与基于(Rosetta 2)的 PHP 版本(php@7.3)之间切换
- android - 在 android studio 的 kotlin 的主要活动中无法访问 EditText id