Index

beginner

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

Example

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.data.*
import arrow.optics.typeclasses.*
import arrow.optics.instances.listk.index.*

val thirdListItemOptional = ListK.index<String>().index(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.

Data types

Module Data types
arrow.data ListK, MapK, NonEmptyList, SequenceK

Hierarchy