TArray
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
}
Content copied to clipboard
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")
}
Content copied to clipboard
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")
}
Content copied to clipboard
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
println("Result $result")
}
Content copied to clipboard
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")
}
Content copied to clipboard