Kotlin extensions for Android: How to use bundleOf
Asked Answered
F

3

26

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.

Francinefrancis answered 17/3, 2018 at 23:21 Comment(0)
B
35

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
)
Bethelbethena answered 17/3, 2018 at 23:23 Comment(1)
Does this auto converts or check if the variable is Parcelable or not?Loris
I
12

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.

Impedance answered 18/3, 2018 at 6:55 Comment(4)
I have added the plugin apply plugin: 'kotlin-android-extensions' , but bundleOf() doesn't resolve itself. Is there something else to set up?Forgiveness
bundleOf has nothing to do with android-kotlin-extension. It is part of core library. Ideally it should be available.Impedance
@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)Clientele
@toobsco42 change bndleOf import to "androidx.core.os.bundleOf"Reconnaissance
A
11

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)
Airwaves answered 20/2, 2019 at 20:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.