How to idiomatically convert NULL types to Kotlin?

I'm new to Kotlin, and I'm looking for tips that rewrite the following code in a more elegant way.

val ts: Long? = 1481710060773 val date: Date? if (ts != null) { date = Date(ts) } 

I tried let , but I think it is not better than the original.

 val ts: Long? = 1481710060773 val date: Date? ts?.let { date = Date(ts) } 

Thanks.

+5
source share
2 answers

You can use the let result as follows:

 val date = ts?.let(::Date) 

Further information on function references can be found using the syntax :: in the Kotlin Documentation

+5
source
 val ts = 1481710060773L val date = Date(ts) 

You do not need to specify ts as the null long type of Long? if you assign it a constant value. Then the Long type is inferred on ts , and the zero check is no longer required.

-1
source

Source: https://habr.com/ru/post/1261310/


All Articles