Description
Introduction
I’d like to propose a small Kotlin DSL for React Native Android native modules, which provides buildReadableMap { … }
and buildReadableArray { … }
helper functions.
This API shape is modeled after Kotlin’s existing Collections DSL—such as buildMap { … }
and buildList { … }
—and wraps the existing Arguments.createMap()
/ Arguments.createArray()
calls in a concise, type-safe DSL, making it much easier to construct nested ReadableMap
and ReadableArray
instances in Kotlin code.
Details
Currently, if you want to assemble a ReadableMap
or ReadableArray
in a Kotlin-based native module, you must do something like:
val map = Arguments.createMap().apply {
putString("name", user.name)
putInt("age", user.age)
val scores = Arguments.createArray()
user.scores.forEach { pushInt(it) }
putArray("scores", scores)
}
With the proposed DSL you would instead write:
val userMap = buildReadableMap {
put("name", user.name)
put("age", user.age)
put("scores") {
user.scores.forEach { add(it) }
}
}
Likewise, building arrays is as simple as:
val numbers = buildReadableArray {
add(1); add(2); add(3)
add { // nested map
put("min", 1)
put("max", 3)
}
}
Discussion points
API shape & naming
- Should the functions be called buildReadableMap/buildReadableArray, or something shorter?
- Should we offer extension variants (e.g. WritableMap.build { … })?
Please share your thoughts! Feedback on API shape, scope, or anything else is very welcome.