Skip to content

Instantly share code, notes, and snippets.

@eoinfogarty
Created July 19, 2017 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eoinfogarty/01c657e4b9efb38238f19fa71620901f to your computer and use it in GitHub Desktop.
Save eoinfogarty/01c657e4b9efb38238f19fa71620901f to your computer and use it in GitHub Desktop.
Kotlin extension to add extras as pairs
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