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.
sure operator. The !! operator asserts that the value is not null or throws an NPE. This should be used in cases where the developer is guaranteeing that the value will never be null .
Kotlin null safety is a procedure to eliminate the risk of null reference from the code. Kotlin compiler throws NullPointerException immediately if it found any null argument is passed without executing any other statements. Kotlin's type system is aimed to eliminate NullPointerException form the code.
Understand non-nullable and nullable variables In Kotlin, there's a distinction between nullable and non-nullable types: Nullable types are variables that can hold null . Non-null types are variables that can't hold null .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With