Created
July 19, 2017 08:15
-
-
Save eoinfogarty/01c657e4b9efb38238f19fa71620901f to your computer and use it in GitHub Desktop.
Kotlin extension to add extras as pairs
This file contains hidden or 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
import android.content.Intent | |
import android.os.Bundle | |
import android.os.Parcelable | |
import java.io.Serializable | |
/** | |
* Intent(context, MyActivity::class.java).withExtras( | |
* KEY_HOGE to "hoge", | |
* KEY_FOO to "foo" | |
* ) | |
*/ | |
fun Intent.withExtras(vararg extras: Pair<String, Any?> = emptyArray()): Intent { | |
val bundle = Bundle() | |
for ((key, value) in extras) { | |
when (value) { | |
is Bundle -> bundle.putBundle(key, value) | |
is Byte -> bundle.putByte(key, value) | |
is ByteArray -> bundle.putByteArray(key, value) | |
is Char -> bundle.putChar(key, value) | |
is CharArray -> bundle.putCharArray(key, value) | |
is CharSequence -> bundle.putCharSequence(key, value) | |
is Float -> bundle.putFloat(key, value) | |
is FloatArray -> bundle.putFloatArray(key, value) | |
is Int -> bundle.putInt(key, value) | |
is IntArray -> bundle.putIntArray(key, value) | |
is Parcelable -> bundle.putParcelable(key, value) | |
is Serializable -> bundle.putSerializable(key, value) | |
is Short -> bundle.putShort(key, value) | |
is ShortArray -> bundle.putShortArray(key, value) | |
is String -> bundle.putString(key, value) | |
is Boolean -> bundle.putBoolean(key, value) | |
is BooleanArray -> bundle.putBooleanArray(key, value) | |
is Double -> bundle.putDouble(key, value) | |
is DoubleArray -> bundle.putDoubleArray(key, value) | |
is Long -> bundle.putLong(key, value) | |
is LongArray -> bundle.putLongArray(key, value) | |
null -> { } | |
else -> throw IllegalArgumentException("Cannot put to bundle, unsupported type: ${value.javaClass}") | |
} | |
} | |
return this.putExtras(bundle) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment