One-liner Intent/Bundle extras extractor in Kotlin!
One day I stumbled upon a custom Delegate that would get an extra using an inner Args
class. I immediately found the feature useful yet it uses some boilerplate code. And for each Activity.
So I wrote simple extensions that would get the extra by lazy:
Pretty easy in fact. Here it is for Fragment
:
extra
would get the extra at runtime when accessing the data. extraNotNull
would do the same, but would crash at runtime if the value was null
.
To learn more about reified
, go read https://proandroiddev.com/how-reified-type-makes-kotlin-so-much-better-7ae539ed0304 ;)
If you wish to enforce required extras as NotNull, I would recommend checking for those in onCreate using a simple requireNotNulls(vararg)
extension (since the extras are actually lazy
, you do need to be explicit):
This way, the Activity
would crash if the required extras were not given. If that’s what you want.
This is a very tiny article and tiny bits of code. But it helped me a lot for my developments. Feel free to review, comment and improve ;)