Hi, I’m a bit stuck on optics, I’m trying to “matc...
# arrow
g
Hi, I’m a bit stuck on optics, I’m trying to “match” the last element of an array, from within a copy method, something like this:
Copy code
person.copy {
    Person.names.last transform { it.replaceFirstChar(Char::uppercase) }
}
Of course the
last
val does not exist, but is there some way to do this?
a
you can create your our
Optional
that matches the last element of a collection. It should be something rought equivalent to:
Copy code
fun <A> last(): Optional<List<A>, A> = Optional(
  getOption = { it.lastOrNull().toOption() },
  set = { lst, elt ->
    if (lst.isEmpty()) lst
    else lst.dropLast(1) + listOf(elt)
  }
)

fun <A, B> Optional<A, List<B>>.last(): Optional<A, B> =
  this compose Optional(
    getOption = { it.lastOrNull().toOption() },
    set = { lst, elt ->
      if (lst.isEmpty()) lst
      else lst.dropLast(1) + listOf(elt)
    }
  )
👍 1
g
Thnx! In the end I needed to create an extension function on Traversal (since I did a filter in between), but it was easily adjusted. So thnx!