Question on nullable


I have this function

  fun dateForSince(s : String) : Date {   val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")   val date = if(s.length != 0) {            formatter.parse(s)   } else {            Date(0)   }   return date   }

that IDEA shows red on the “date” in “return date”.  It wants me to put a “?” after the Date in the class definition.  The attached screenshot shows the effect.

My question is if date has a value by virtue of the the if-else, why does the compiler insist I mark the return value as possibly null?  It is because the formatter.parse() call might throw an exception?

date.png (78.3 KB)


SimpleDateFormat is an Java class => formatter.parse(s) returns Date? (nullable Date) => val date : Date?

You can write formatter.parse(s).sure() (convert to not nullable Date), but remember that it will throw NPE if formatter.parse(s) returns null.