Skip to content

Instantly share code, notes, and snippets.

@ericksli
Last active March 20, 2024 19:51
Show Gist options
  • Save ericksli/58c3b0082ba933dde6e908c2d3822408 to your computer and use it in GitHub Desktop.
Save ericksli/58c3b0082ba933dde6e908c2d3822408 to your computer and use it in GitHub Desktop.
React Native Kotlin extension functions for creating WritableMap and WritableArray #android #react-native #kotlin
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.WritableArray
import com.facebook.react.bridge.WritableMap
fun writableMapOf(vararg values: Pair<String, *>): WritableMap {
val map = Arguments.createMap()
for ((key, value) in values) {
when (value) {
null -> map.putNull(key)
is Boolean -> map.putBoolean(key, value)
is Double -> map.putDouble(key, value)
is Int -> map.putInt(key, value)
is String -> map.putString(key, value)
is WritableMap -> map.putMap(key, value)
is WritableArray -> map.putArray(key, value)
else -> throw IllegalArgumentException("Unsupported value type ${value::class.java.name} for key [$key]")
}
}
return map
}
fun writableArrayOf(vararg values: Any?): WritableArray {
val array = Arguments.createArray()
for (value in values) {
when (value) {
null -> array.pushNull()
is Boolean -> array.pushBoolean(value)
is Double -> array.pushDouble(value)
is Int -> array.pushInt(value)
is String -> array.pushString(value)
is WritableArray -> array.pushArray(value)
is WritableMap -> array.pushMap(value)
else -> throw IllegalArgumentException("Unsupported type ${value::class.java.name}")
}
}
return array
}
@axelinternet
Copy link

This is great! Thanks, RN Kotlin documentation is a mess so this saved some time

@kyleclegg
Copy link

This is helpful! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment