Common sequences

I have the following snippet. The second variable declaration doesn't compile:

type 
  Coin = ref object
  Pen  = ref object

let 
  yes : seq[ref object] = @[Coin(), Coin(), Coin()]  #Compiles
  no  : seq[ref object] = @[Coin(), Pen(), Coin()]   #Does not compile

      

Is it possible in nim to have common seqs like java list?

+3


source to share


1 answer


Nym sequences are common, but you don't put the same objects in them. In Java, all non-primitive types (including arrays) inherit directly or indirectly from the superclass Object , and therefore, given a type List<Object>

, you can do anything in it. But in Him, not everything has to have the same root, and in your case, while the objects look the same, they are treated as different types. So you need to create a class hierarchy like java:

type
  BaseRef = ref object of TObject
  CoinRef = ref object of BaseRef
  PenRef = ref object of BaseRef

let
  test1: seq[BaseRef] = @[(BaseRef)CoinRef(), CoinRef(), CoinRef()]
  test2: seq[BaseRef] = @[(BaseRef)CoinRef(), PenRef(), CoinRef()]

      

Note that the list constructor @[]

still needs to be tweaked in the right direction to convert the first element to the base type, or you end up with inequality (a is seq[BaseRef]

not the same as seq[CoinRef]

what would be the result of type inference).

If you need to keep separate roots while being refs for some reason, it should be good to use them directly, for which you can create helper procs:



type 
  AnyRef = ref object
  Coin = ref object
  Pen  = ref object

proc `^`(x: Coin): AnyRef = cast[AnyRef](x)
proc `^`(x: Pen): AnyRef = cast[AnyRef](x)

let 
  yes : seq[AnyRef] = @[^Coin(), ^Coin(), ^Coin()]
  no  : seq[AnyRef] = @[^Coin(), ^Pen(), ^Coin()]

      

Or perhaps create a procs converter that doesn't require an explicit conversion for all elements, only the first one, for example with an inheritance version:

type 
  AnyRef = ref object
  Coin = ref object
  Pen  = ref object

converter toAnyRef(x: Coin): AnyRef = cast[AnyRef](x)
converter toAnyRef(x: Pen): AnyRef = cast[AnyRef](x)

let 
  yes : seq[AnyRef] = @[Coin().toAnyRef, Coin(), Coin()]
  no  : seq[AnyRef] = @[Coin().toAnyRef, Pen(), Coin()]

      

+4


source







All Articles