Kotlin extensions for Android: How to use bundleOf
15,041
Solution 1
If it takes a vararg
, you have to supply your arguments as parameters, not a lambda. Try this:
val bundle = bundleOf(
Pair("KEY_PRICE", 50.0),
Pair("KEY_IS_FROZEN", false)
)
Essentially, change the {
and }
brackets you have to (
and )
and add a comma between them.
Another approach would be to use Kotlin's to
function, which combines its left and right side into a Pair
. That makes the code even more succinct:
val bundle = bundleOf(
"KEY_PRICE" to 50.0,
"KEY_IS_FROZEN" to false
)
Solution 2
How about this?
val bundle = bundleOf (
"KEY_PRICE" to 50.0,
"KEY_IS_FROZEN" to false
)
to
is a great way to create Pair
objects. The beauty of infix function with awesome readability.
Solution 3
Just to complete the other answers:
First, to use bundleOf
, need to add implementation 'androidx.core:core-ktx:1.0.0'
to the build.gradle
then:
var bundle = bundleOf("KEY_PRICE" to 50.0, "KEY_IS_FROZEN" to false)
Related videos on Youtube
Comments
-
Malwinder Singh almost 2 years
Documentation says:
fun bundleOf(vararg pairs: Pair<String, Any?>): Bundle
Returns a new Bundle with the given key/value pairs as elements.
I tried:
val bundle = bundleOf { Pair("KEY_PRICE", 50.0) Pair("KEY_IS_FROZEN", false) }
But it is showing error.
-
Etienne Lawlor over 5 yearsI have added the plugin
apply plugin: 'kotlin-android-extensions'
, butbundleOf()
doesn't resolve itself. Is there something else to set up? -
Chandra Sekhar over 5 yearsbundleOf has nothing to do with android-kotlin-extension. It is part of core library. Ideally it should be available.
-
sbearben over 5 years@toobsco42 bundleOf is part of the Android KTX extension functions. Check out the docs here: developer.android.com/kotlin/ktx (it's in the androidx.core.os package)
-
Oleksandr Bodashko about 5 years@toobsco42 change bndleOf import to "androidx.core.os.bundleOf"
-
Rishabh Deep Singh over 2 yearsDoes this auto converts or check if the variable is
Parcelable
or not?