Skip to content

Instantly share code, notes, and snippets.

@jamolkhon
Last active November 26, 2018 10:35
Show Gist options
  • Save jamolkhon/f79ebf21d06b4621218754ee6f739f37 to your computer and use it in GitHub Desktop.
Save jamolkhon/f79ebf21d06b4621218754ee6f739f37 to your computer and use it in GitHub Desktop.
building an android bundle from map (most likely doesn't work, i haven't checked yet)
@SuppressLint("NewApi")
@Suppress("UNCHECKED_CAST")
fun Map<String, Any?>.toBundle(): Bundle = Bundle().apply {
[email protected] { entry ->
val (key, value) = entry
when (value) {
is Boolean -> putBoolean(key, value)
is Int -> putInt(key, value)
is Byte -> putByte(key, value)
is Char -> putChar(key, value)
is Short -> putShort(key, value)
is Float -> putFloat(key, value)
is Double -> putDouble(key, value)
is String -> putString(key, value)
is CharSequence -> putCharSequence(key, value)
is Parcelable -> putParcelable(key, value)
is Serializable -> putSerializable(key, value)
is Size -> putSize(key, value)
is SizeF -> putSizeF(key, value)
is Bundle -> putBundle(key, value)
is BooleanArray -> putBooleanArray(key, value)
is IntArray -> putIntArray(key, value)
is ByteArray -> putByteArray(key, value)
is CharArray -> putCharArray(key, value)
is ShortArray -> putShortArray(key, value)
is FloatArray -> putFloatArray(key, value)
is DoubleArray -> putDoubleArray(key, value)
is SparseArray<*> -> if (value.size() > 0) when (value.valueAt(0)) {
is Parcelable -> putSparseParcelableArray(key, value as SparseArray<out Parcelable>?)
else -> throw UnsupportedOperationException()
}
is Array<*> -> if (value.isNotEmpty()) when (value[0]) {
is CharSequence -> putCharSequenceArray(key, value as Array<out CharSequence>?)
is Parcelable -> putParcelableArray(key, value as Array<out Parcelable>?)
is String -> putStringArray(key, value as Array<out String>?)
else -> throw UnsupportedOperationException()
}
is ArrayList<*> -> if (value.isNotEmpty()) when (value[0]) {
is Int -> putIntegerArrayList(key, value as java.util.ArrayList<Int>?)
is Parcelable -> putParcelableArrayList(key, value as java.util.ArrayList<out Parcelable>?)
is String -> putStringArrayList(key, value as java.util.ArrayList<String>)
is CharSequence -> putCharSequenceArrayList(key, value as java.util.ArrayList<CharSequence>)
else -> throw UnsupportedOperationException()
}
else -> throw UnsupportedOperationException()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment