【问题标题】:Kotlin Date Error "Type mismatch: inferred type is Date? but Date was expected"Kotlin 日期错误“类型不匹配:推断类型为日期?但预期日期”
【发布时间】:2021-05-04 01:34:06
【问题描述】:
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): 类型不匹配:推断类型是日期?但预计日期

【问题讨论】:

  • 我建议你不要使用SimpleDateFormatDate。这些类设计不良且过时,尤其是前者,尤其是出了名的麻烦。而是使用LocalDateLocalDateTimeDateTimeFormatter,均来自java.time, the modern Java date and time API

标签: date kotlin types mismatch


【解决方案1】:

SimpleDateFormat.parse 是一个 java 函数,它可以返回一个可为空的 Date Date? 。由于 enDate 被定义为 Date 并且您试图分配给可为空的 Date,kotlin 试图避免它并引发错误。

您可以使用 UNSAFE !! 运算符

 enDate=formatter.parse(endTime)!!

或显式处理空大小写

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

【讨论】:

  • 可能值得指出,parse() 具有可为空类型的原因是因为如果字符串不是有效日期,它会返回 null。所以遇到这种情况就需要考虑如何处理了。 (当然,还有其他方法可以处理它。  但是编译器会强制你以某种方式处理它。)
  • teşekkürler。 !! ile sorun çözüldü。