Kotlin 日期错误 "Type mismatch: inferred type is Date? but Date was expected"

Kotlin Date Error "Type mismatch: inferred type is Date? but Date was expected"

lateinit var endTime:String
lateinit var enDate:Date

val formatter= SimpleDateFormat("dd.MM.yyyy, HH:mm:ss")

endTime=tarihBul()+", 00:00:00"

**enDate=formatter.parse(endTime)  -->213**
miliseconds=enDate.time


   private fun tarihBul():String {

        val tarihFormat= SimpleDateFormat("dd.MM.yyyy")
        val tarih= Date()
        val simdiTarih=tarihFormat.format(tarih)


        return simdiTarih.toString()

w: F:\Dersler\Kotlin_uygulamalar\Namazvakitleri\app\src\main\java\com\erdemselvi\namazvakitleri\widget\VakitlerWidget.kt: (213, 16): Type mismatch: inferred type is Date? but Date was expected

SimpleDateFormat.parse 是一个 java 函数,它可以 return 一个可为 null 的日期 Date? 。由于 enDate 被定义为 Date 并且您正试图分配给可为 null 的日期,kotlin 会尝试避免它并抛出错误。

您可以使用 UNSAFE !! 运算符

 enDate=formatter.parse(endTime)!!

或显式处理 null 大小写

 enDate=formatter.parse(endTime)?.let{ YOUR LOGIC TO THROW ERROR OR DEFAULT VALUE}