androidkotlinandroid-bundleandroid-ktx

Kotlin extensions for Android: How to use bundleOf


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.


Solution

  • 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
    )