Index provides an Optional for a structure S to focus in optional A at a given index I.


If for a structure S the optionally focus A can be indexed by I then Index can create an Optional with focus at S for a given index I. We can use that Optional to safely operate on that focus S i.e. operating on items in a List based on the index position.

import arrow.optics.typeclasses.*

val thirdListItemOptional = Index.index<ListKOf<String>, Int, String>(3)

thirdListItemOptional.set(listOf("0", "1", "2", "3").k(), "newValue")
// ListK(list=[0, 1, 2, newValue])
thirdListItemOptional.set(listOf("0", "1", "2").k(), "newValue")
// ListK(list=[0, 1, 2])
thirdListItemOptional.setOption(listOf("0", "1", "2").k(), "newValue")
// None

Creating your own Index instances

Arrow provides Index instances for some common datatypes both in Arrow and the Kotlin stdlib that can be indexed, like ListK and MapK. You can look them up by calling Index.index().

You may create instances of Index for your own datatypes which you will be able to use as demonstrated in the example above.

See Deriving and creating custom typeclass to provide your own Index instances for custom datatypes.


The following datatypes in Arrow provide instances that adhere to the Index typeclass.