ListK wraps over the platform List type to make it a type constructor.

It can be created from Kotlin List type with a convenient k() function.

import arrow.*
import arrow.core.*

listOf(1, 2, 3).k()
// [1, 2, 3]

For most use cases, you will never use ListK directly, but rather List directly with the extension functions that Arrow projects over it.

ListK implements operators from many useful typeclasses.

The @extension type class processor expands all type class combinators that ListK provides automatically over List

For instance, it has combineK from the SemigroupK typeclass.

It can be used to cheaply combine two lists:

import arrow.core.extensions.list.semigroupK.*

val hello = listOf('h', 'e', 'l', 'l', 'o')
val commaSpace = listOf(',', ' ')
val world = listOf('w', 'o', 'r', 'l', 'd')

// [h, e, l, l, o, ,,  , w, o, r, l, d]

The functions traverse and sequence come from Traverse.

Traversing a list creates a new container Kind<F, A> by combining the result of a function applied to each element:

import arrow.core.*
import arrow.core.extensions.option.applicative.*
import arrow.core.extensions.list.traverse.*

val numbers = listOf(Math.random(), Math.random(), Math.random())
numbers.traverse(Option.applicative(), { if (it > 0.5) Some(it) else None })
// None

and complements the convenient function sequence() that converts a list of ListK<Kind<F, A>> into a Kind<F, ListK<A>>:

fun andAnother() = Some(Math.random())

val requests = listOf(Some(Math.random()), andAnother(), andAnother())
// Some([0.18292943212401236, 0.32501023785847993, 0.5322721771854795])

If you want to aggregate the elements of a list into any other value, you can use foldLeft and foldRight from Foldable.

Folding a list into a new value, String in this case, starting with an initial value and a combine function:

listOf('a', 'b', 'c', 'd', 'e').k().foldLeft("-> ") { x, y -> x + y }
// -> abcde

Or you can apply a list of transformations using ap from Applicative.

import arrow.core.extensions.*
import arrow.core.extensions.list.apply.*

listOf(1, 2, 3).ap(listOf({ x: Int -> x + 10}, { x: Int -> x * 2}))
// [11, 2, 12, 4, 13, 6]

Do you like Arrow?

Arrow Org