arrow-fx-stm / arrow.fx.stm / TArray

TArray

data class TArray<A>

A TArray is an array of transactional variables.

Creating TArray

Similar to normal arrays there are a few ways to create a TArray:

import arrow.fx.stm.TArray
import arrow.fx.stm.atomically

suspend fun example() {
  //sampleStart
  // Create a size 10 array and fill it by using the construction function.
  TArray.new(10) { i -> i * 2 }
  // Create a size 10 array and fill it with a constant
  TArray.new(size = 10, 2)
  // Create an array from `vararg` arguments:
  TArray.new(5, 2, 10, 600)
  // Create an array from any iterable
  TArray.new(listOf(5,4,3,2))
  //sampleEnd
}

Reading a value from the array

import arrow.fx.stm.TArray
import arrow.fx.stm.atomically

suspend fun main() {
  //sampleStart
  val tarr = TArray.new(size = 10, 2)
  val result = atomically {
    tarr[5]
  }
  //sampleEnd
  println("Result $result")
}

Setting a value in the array

import arrow.fx.stm.TArray
import arrow.fx.stm.atomically

suspend fun main() {
  //sampleStart
  val tarr = TArray.new(size = 10, 2)
  val result = atomically {
    tarr[5] = 3

    tarr[5]
  }
  //sampleEnd
  println("Result $result")
}

Transform the entire array

import arrow.fx.stm.TArray
import arrow.fx.stm.atomically

suspend fun main() {
  //sampleStart
  val tarr = TArray.new(size = 10, 2)
  val result = atomically {
    tarr.transform { it + 1 }
  }
  //sampleEnd
}

Folding the array

import arrow.fx.stm.TArray
import arrow.fx.stm.atomically

suspend fun main() {
  //sampleStart
  val tarr = TArray.new(size = 10, 2)
  val result = atomically {
    tarr.fold(0) { acc, v -> acc + v }
  }
  //sampleEnd
  println("Result $result")
}

Functions

equals fun equals(other: Any?): Boolean
hashCode fun hashCode(): Int
size fun size(): Int

Companion Object Functions

new suspend fun <A> new(size: Int, f: (Int) -> A): TArray<A>
suspend fun <A> new(size: Int, a: A): TArray<A>
suspend fun <A> new(vararg arr: A): TArray<A>
suspend fun <A> new(xs: Iterable<A>): TArray<A>

Do you like Arrow?

Arrow Org
<