Last active
November 11, 2022 07:10
-
-
Save Urdzik/df00d70414db110631773b7871981f50 to your computer and use it in GitHub Desktop.
Kotlin Delegated(Bundel)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Universal put function for bundel | |
fun <T> Bundle.put(key: String, value: T) { | |
when (value) { | |
is Boolean -> putBoolean(key, value) | |
is String -> putString(key, value) | |
is Int -> putInt(key, value) | |
is Short -> putShort(key, value) | |
is Long -> putLong(key, value) | |
is Byte -> putByte(key, value) | |
is ByteArray -> putByteArray(key, value) | |
is Char -> putChar(key, value) | |
is CharArray -> putCharArray(key, value) | |
is CharSequence -> putCharSequence(key, value) | |
is Float -> putFloat(key, value) | |
is Bundle -> putBundle(key, value) | |
is Parcelable -> putParcelable(key, value) | |
is Serializable -> putSerializable(key, value) | |
else -> throw IllegalStateException("Type of property $key is not supported") | |
} | |
} | |
// Custom delegated for bundel | |
class FragmentArgumentDelegate<T : Any> : | |
ReadWriteProperty<Fragment, T> { | |
@Suppress("UNCHECKED_CAST") | |
override fun getValue( | |
thisRef: Fragment, | |
property: KProperty<*> | |
): T { | |
val key = property.name | |
return thisRef.arguments | |
?.get(key) as? T | |
?: throw IllegalStateException("Property ${property.name} could not be read") | |
} | |
override fun setValue( | |
thisRef: Fragment, | |
property: KProperty<*>, value: T | |
) { | |
val args = thisRef.arguments | |
?: Bundle().also(thisRef::setArguments) | |
val key = property.name | |
args.put(key, value) | |
} | |
} | |
//Delegated without null safety | |
class FragmentNullableArgumentDelegate<T : Any?> : | |
ReadWriteProperty<Fragment, T?> { | |
@Suppress("UNCHECKED_CAST") | |
override fun getValue( | |
thisRef: Fragment, | |
property: KProperty<*> | |
): T? { | |
val key = property.name | |
return thisRef.arguments?.get(key) as? T | |
} | |
override fun setValue( | |
thisRef: Fragment, | |
property: KProperty<*>, value: T? | |
) { | |
val args = thisRef.arguments | |
?: Bundle().also(thisRef::setArguments) | |
val key = property.name | |
value?.let { args.put(key, it) } ?: args.remove(key) | |
} | |
} | |
// Function for easy use | |
fun <T : Any> argument(): ReadWriteProperty<Fragment, T> = | |
FragmentArgumentDelegate() | |
fun <T : Any> argumentNullable(): ReadWriteProperty<Fragment, T?> = | |
FragmentNullableArgumentDelegate() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment