https://kotlinlang.org logo
#arrow
Title
# arrow
d

dave08

03/29/2023, 1:41 PM
Already the second time (now in unit tests) that it would be nice to have something in the Kotlinx serialization optics library a way to get a lens to a
List<String>
on the `name`s here:
Copy code
[{ "id":1, "name": "this"}, {"id":2, "name": "that"}]
s

Sam

03/29/2023, 1:43 PM
If only this was Groovy, you could just write
list.name
🧌
s

simon.vergauwen

03/29/2023, 1:44 PM
JsonPath.every.select("name")
works for this, no?
JsonPath.every.select("name").getOrNull(jsonElement)
d

dave08

03/29/2023, 1:45 PM
Nope, that gives a
List<JsonElement>
s

simon.vergauwen

03/29/2023, 1:45 PM
JsonPath.every.select("name").string.getOrNull(jsonElement)
a

Alejandro Serrano Mena

03/29/2023, 1:47 PM
you always need something like
string
to ensure that you’re targeting the right type of element
d

dave08

03/29/2023, 1:48 PM
👍🏼 It seems like that does it, but there's no
getOrNull
there, just
getAll
...?
This is all a bit confusing about Optics... I'm still not sure what returns what and when...
a

Alejandro Serrano Mena

03/29/2023, 1:49 PM
I think it should be
getAll
in this case, since you want to return a list of elements
d

dave08

03/29/2023, 1:50 PM
image.png
a

Alejandro Serrano Mena

03/29/2023, 1:50 PM
• `getAll`returns List<T>, available for Every, Optional, Prism, Lens •
getOrNone
returns Option<T>, available for Optional, Prism, Lens • `get`` returns T, available for Lens
PEvery<JsonElement, JsonElement, String, String
is equivalent to
Every<JsonElement, String>
d

dave08

03/29/2023, 1:52 PM
So I'm using Every here? Why do PTraversal and PSetter appear there and when would I use them?
For setting that list "in place"?
a

Alejandro Serrano Mena

03/29/2023, 1:57 PM
sorry, my bad, I meant to mention
Every
in the list above
the reason why you get the others is because optics form a hierarchy
a Every is a Traversal, which is both a Fold (which is the base interface containing
getAll
) and a Setter (which is the base interface containing
modify
)
3 Views