Reputation: 6949
I am new to Kotlin, and I am looking for advises rewriting the following code to more elegant way.
val ts: Long? = 1481710060773
val date: Date?
if (ts != null) {
date = Date(ts)
}
I have tried let
, but I think it is not better than the original one.
val ts: Long? = 1481710060773
val date: Date?
ts?.let {
date = Date(ts)
}
Thanks.
Upvotes: 6
Views: 458
Reputation: 41638
You can use result of let
call like so:
val date = ts?.let(::Date)
You can find more about function references using ::
syntax in Kotlin documentation
Upvotes: 5
Reputation: 8191
val ts = 1481710060773L
val date = Date(ts)
You don't need to specify ts
as a nullable long type Long?
if you are assigning a constant value to it. Then the type Long
is inferred to ts
and no null-check is necessary anymore.
Upvotes: -1