0

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.

Vencat
  • 1,272
  • 11
  • 36
  • One way would be using arrow AtomicRef https://arrow-kt.io/docs/1.1.0/apidocs/arrow-core/arrow.core.continuations/-atomic-ref/index.html#atomicref but it throws runtime exception if it's not initialized with a value. – Vencat Feb 04 '23 at 15:19

1 Answers1

1

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.

serras
  • 2,165
  • 2
  • 13
  • 11
  • Btw, making the constructor private or making the `invoke` function take no arguments is not part of the pattern, I just wrote those for the sake of a concrete example. – serras Feb 06 '23 at 08:23
  • Note also that Arrow 1.2 is going to ship with a new `arrow-atomic` library which exposes a constructor without `suspend`. Unfortunately the only docs for now are [their implementation](https://github.com/arrow-kt/arrow/blob/main/arrow-libs/core/arrow-atomic/src/commonMain/kotlin/arrow/atomic/Atomic.kt), but this solves your problem in a forward-compatible way. – serras Feb 06 '23 at 09:04
  • Alternatively, you can use `suspend fun Thingy() = Thingy(Atomic(0))`, if you prefer to declare it somewhere other than in the `Companion`. – Jorn Feb 06 '23 at 10:25