25

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.

Malwinder Singh
  • 6,644
  • 14
  • 65
  • 103

3 Answers3

33

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
)
Todd
  • 30,472
  • 11
  • 81
  • 89
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.

Chandra Sekhar
  • 18,914
  • 16
  • 84
  • 125
  • 3
    I have added the plugin `apply plugin: 'kotlin-android-extensions'` , but `bundleOf()` doesn't resolve itself. Is there something else to set up? – Etienne Lawlor Sep 07 '18 at 06:17
  • bundleOf has nothing to do with android-kotlin-extension. It is part of core library. Ideally it should be available. – Chandra Sekhar Sep 07 '18 at 08:56
  • 3
    @toobsco42 bundleOf is part of the Android KTX extension functions. Check out the docs here: https://developer.android.com/kotlin/ktx (it's in the androidx.core.os package) – sbearben Nov 28 '18 at 17:37
  • @toobsco42 change bndleOf import to "androidx.core.os.bundleOf" – Oleksandr Bodashko Feb 13 '19 at 18:24
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)
A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128