How to create a member variable of Arrow Atomic in kotlin

222 Views Asked by At

Arrow-fx has a type Atomic which is similar to java AtomicRef but with an initial value, which means I don't need to check every time while accessing the atomic value whether it's null.

Here is a simple example

import arrow.fx.coroutines.*

suspend fun main() {
  val count = Atomic(0)

  (0 until 20_000).parTraverse {
    count.update(Int::inc)
  }
  println(count.get())
}

Now I would like to create a class member variable with this type, but since it's only possible to initialize within a suspend function I would like to know the possibility here.

1

There are 1 best solutions below

3
serras On

The easiest way is to make a "fake constructor" in the companion object.

public class Thingy private constructor(
  val count: Atomic<Int>
) {
  companion object {
    suspend fun invoke() = Thingy(Atomic(0))
  }
}

Now when you write Thingy(), you're actually calling the invoke function in Thingy.Companion. For that function there are no restrictions over suspending, so you can initialize Atomic as shown above.