I have the following extension functions that allow me to pass bundle data items between my applications activities and fragments.
inline fun <reified T : Any> Activity.extra(key: String, default: T? = null): Lazy<T?> = lazy {
val value: Any? = intent?.extras?.get(key)
if (value is T) value else default
}
inline fun <reified T : Any> Activity.extraNotNull(key: String, default: T? = null): Lazy<T> = lazy {
val value: Any? = intent?.extras?.get(key)
requireNotNull(if (value is T) value else default) { MISSING_MANDATORY_KEY + key }
}
inline fun <reified T : Any> Fragment.extra(key: String, default: T? = null): Lazy<T?> = lazy {
val value: Any? = arguments?.get(key)
if (value is T) value else default
}
inline fun <reified T : Any> Fragment.extraNotNull(key: String, default: T? = null): Lazy<T> = lazy {
val value: Any? = arguments?.get(key)
requireNotNull(if (value is T) value else default) { MISSING_MANDATORY_KEY + key }
}
the .get(key) methods are all now deprecated and i cannot see how to replace them.
as it looks as though i will need specific .getXxxx() calls now based on the passed data type.
what options do i have?
i like that these extension functions allow me to use one liners such as this:-
private val bookId by extraNotNull<Long>(EXTRA_KEY_MY_ID)
private val initialItemContentId by extraNotNull<String>(EXTRA_KEY_CONTENT_ID)
private val initialFilePath by extraNotNull<String>(EXTRA_KEYFILE_PATH)
private val initialMinPageNumber by extraNotNull<Int>(EXTRA_KEY_MIN_PAGE_NUMBER)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
url = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
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