Android Kotlin调用kotlin.concurrency.thread报错:Unresolved reference: thread
解决Kotlin中
thread函数找不到的问题 你遇到的Unresolved reference: thread错误,主要是因为缺少正确的导入或依赖配置,下面一步步帮你解决:
第一步:添加正确的导入语句
thread函数属于kotlin.concurrent包,你需要在代码文件顶部添加这个导入:import kotlin.concurrent.thread没有这个导入的话,编译器找不到这个扩展函数。
第二步:确认Kotlin标准库依赖
在Android项目的build.gradle(Module level)文件中,确保已经引入了Kotlin标准库依赖(通常Android Studio创建项目时会自动添加,但如果手动修改过配置可能会丢失):dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" // 如果你用的是Kotlin 1.8+,也可以用kotlin-stdlib-jdk8,包含更多JDK8相关API // implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" }记得把
$kotlin_version替换成你项目中使用的Kotlin版本号,比如1.9.20。额外的代码优化建议
你的代码还有两个小问题可以优化:- Kotlin中建议使用
Int而非Java的Integer,所以参数类型可以改成userId: Int - 你创建的
CustomExceptionHandler(context)只是实例化了对象,但没有绑定到线程上,应该在线程块内部设置未捕获异常处理器:
或者也可以直接在fun identify(userId: Int) { thread { Thread.currentThread().uncaughtExceptionHandler = CustomExceptionHandler(context) DoStuffClass.doStuff(context, userId) } }thread函数的参数中指定(前提是CustomExceptionHandler实现了Thread.UncaughtExceptionHandler接口):fun identify(userId: Int) { thread(uncaughtExceptionHandler = CustomExceptionHandler(context)) { DoStuffClass.doStuff(context, userId) } }
- Kotlin中建议使用
内容的提问来源于stack exchange,提问作者Abraham P
相关产品推荐
相关产品推荐

