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
swipeViewfrom ever beingnull.Local variable
If
swipeViewis a local variable then you can declare it non-null when initially assigning it:Function argument
If
swipeViewis a function argument then you can use a default argument to ensure it is nevernull:Class property
Read-only
If
swipeViewis a read-only class property (i.e.val) then you can use Kotlin's built-inLazy:Mutable
If
swipeViewis a mutable class property (i.e.var) then you can define your own delegate similar toLazybut mutable. e.g. The following is based on kotlin/Lazy.kt:Usage:
The
initializerwill only be called ifswipeViewis read and is not initialized yet (from a previous read or write).