Lazy initialization in Pony

54 Views Asked by At

Here's what I'd like to do

# Ruby
class Foo
  def bar
    @bar ||= []
  end
end

Here's what I'm starting with:

 // Pony pseudocode
 class Foo
   var _bar: Optional(Array(I32))
   fun ref bar(): Array(I32) ref =>
     if _bar == None then
       _bar = Some([])
     end
     _bar.unbox()
1

There are 1 best solutions below

0
Florian Weimer On

Pony does not have a built option type. Instead, you can write a sum type (…. | None), with a None alternative. Pattern matching can be used to recover the alternatives, based on their types:

class Foo
  var _bar: (Array[I32] ref | None) = None
  fun ref bar(): Array[I32] ref =>
    match _bar
      | let bar': Array[I32] => bar'
      | None =>
        let bar'' = Array[I32]
        _bar = bar''
        bar''
    end

Note that Pony use […] around type arguments, not parentheses.