In Kotlin, is there any shorter syntax for this code:
if(swipeView == null){
swipeView = view.find<MeasureTypePieChart>(R.id.swipeableView)
}
First i tried this:
swipeView ?: view.find<MeasureTypePieChart>(R.id.swipeableView)
but then i realised that wasn't an assignment, so that code does nothing. Then i tried:
swipeView = swipeView ?: view.find<MeasureTypePieChart>(R.id.swipeableView)
Which works, but it a bit verbose. I would expect something like this:
swipeView ?= view.find<MeasureTypePieChart>
But unfortunately that doesn't work. Is there any way of accomplish this with a short syntax?
I know i can do this:
variable?.let { it = something } which works.
Shorter syntax would be to avoid
swipeView
from ever beingnull
.Local variable
If
swipeView
is a local variable then you can declare it non-null when initially assigning it:Function argument
If
swipeView
is a function argument then you can use a default argument to ensure it is nevernull
:Class property
Read-only
If
swipeView
is a read-only class property (i.e.val
) then you can use Kotlin's built-inLazy
:Mutable
If
swipeView
is a mutable class property (i.e.var
) then you can define your own delegate similar toLazy
but mutable. e.g. The following is based on kotlin/Lazy.kt:Usage:
The
initializer
will only be called ifswipeView
is read and is not initialized yet (from a previous read or write).