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
Multithreading 错误要求类型不匹配:找到线程:度量单位_Multithreading_Kotlin - Fatal编程技术网

Multithreading 错误要求类型不匹配:找到线程:度量单位

Multithreading 错误要求类型不匹配:找到线程:度量单位,multithreading,kotlin,Multithreading,Kotlin,为什么在类中创建线程时会出现错误类型不匹配Required:Thread Found:Unit class MainActivity : AppCompatActivity() { private var thread: Thread? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentV

为什么在类中创建线程时会出现错误类型不匹配Required:Thread Found:Unit

class MainActivity : AppCompatActivity() {

    private var thread: Thread? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        thread = Thread {
            try {
                println("Hello")
            } catch (ex: IOException) {
                ex.printStackTrace()
            }
        }.start()
    }
}

你需要把你的声明和开始分开。在这里,您将
.start()
的值分配给
线程
的值。该值为
单位
,因为
.start()
有一个空返回值

你可以做:

thread = Thread {
    try {
        println("Hello")
    } catch (ex: IOException) {
        ex.printStackTrace()
    }
}

thread.start()