Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to idiomatically transform nullable types in Kotlin?

Tags:

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.

like image 553
iForests Avatar asked Dec 15 '16 07:12

iForests


People also ask

What is the idiomatic way to deal with nullable values referencing or converting them?

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 .

What is null safety in Kotlin android?

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.

What is the difference between nullable and non-nullable properties in Android?

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 .


1 Answers

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

like image 125
miensol Avatar answered Sep 26 '22 16:09

miensol