【发布时间】:2022-11-20 12:34:41
【问题描述】:
I wrote an extension function to get an element of an JSON object by its name:
fun JSONObject.obj (name: String): JSONObject? =
try { this.getJSONObject(name) }
catch (e: JSONException) { null }
Now I want to extend this for nested JSON objects. I wrote the following:
tailrec fun JSONObject.obj (first: String, vararg rest: String): JSONObject? =
if (rest.size == 0)
obj(first)
else
obj(first)?.obj(rest[0], *rest.drop(1).toTypedArray())
But this looks quite inefficient to me.
What is the best way to slice a vararg argument?
【问题讨论】:
-
If you're just asking about the slicing, a
varargis just an array, so you can userest.sliceArray(1 until rest.size)to avoid converting to a list and back -
@cactustictacs Using
sliceArrayis probably also not efficient. It seems to be a misnomer, because the function copies the array. -
It makes a new array of the length you want and copies items into it, i.e. fills it with references to the Strings in the original array. You're not going to get much more efficient than that - what else are you expecting? What do you mean bysliceif not copying a range of elements into another array?