Checking if LocalDateTIme is null in a conditional

sisternight438 :

Here I have a function that formats a string to a LocalDateTime and returns it.

val dateSentFormatted = timeFormatted(record.data.dateTime);
private fun timeFormatted(dateEmailSent: String?): LocalDateTime {
    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd:HH:mm:ss");
    return LocalDateTime.parse(dateEmailSent, formatter);
}

My question is I wanted an if statement to run on it elsewhere in my file to check whether it's null as in:

if (!dateSentFormatted != null ) {

}

But it doesn't like that, how else can I check whether a variable of type LocalDateTime is empty in an if statement?

ysakhno :

Method parse(CharSequence, DateTimeFormatter) of the java.time.LocalDateTime class does not accept null as the character sequence (first parameter), so you have to make an explicit null-check and rewrite the return from your function as

return if (dateEmailSent != null) LocalDateTime.parse(dateEmailSent, formatter) else null

(you don't have to have semicolons (;) by the way)

Moreover, the return type of your function as written is non-nullable, so you'll have to change it to LocalDateTime?.

And, since there is no point in creating a parser/formatter if it is not going to be used in case of dateEmailSent being null, I suggest to rewrite the entire function as follows:

fun timeFormatted(dateEmailSent: String?) = if (dateEmailSent != null) {
    LocalDateTime.parse(dateEmailSent, DateTimeFormatter.ofPattern("yyyy-MM-dd:HH:mm:ss"))
} else null

The last part is up to you, the rest is pretty much mandatory if you want to achieve the functionality you described in your question.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=195119&siteId=1