Search code examples
datekotlintypesmismatch

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


Solution

  • SimpleDateFormat.parse is a java function, which can return a nullable Date Date? . As enDate is defined as Date and you are trying to assign to nullable Date, kotlin tries to avoid it and throws an error.

    You can either use the UNSAFE !! operator

     enDate=formatter.parse(endTime)!!
    

    or handle null case explicitly

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