#1873 Emulation of generics => fails

Xan Sat 14 Apr 2012

Hi,

Although there is no generic in Fantom, I want to "emulate" this with this code:

abstract class Algorithm {
    const static Str name
    const static Int version
   |Obj -> Obj| function

   new make(Str nom, Int ver, |Obj -> Obj| alg) {
       name = nom
       version = ver
       function = alg
   }
}

 class SizeAlg : Algorithm {
  const static Str name := "Size"
  const static Int version := 1
  |Str -> Int | function := type.method("sizeof").func

   static Int sizeof(Str a) {
       return a.size
   }
}

when I compile, I receive:

fan generic.fan 
/home/xan/proves/yot-ng/propi/codi/aranya-fantom/generic.fan(32,2): Cannot override non-virtual slot 'generic_0::Algorithm.version'
/home/xan/proves/yot-ng/propi/codi/aranya-fantom/generic.fan(33,2): Cannot override non-virtual slot 'generic_0::Algorithm.function'
/home/xan/proves/yot-ng/propi/codi/aranya-fantom/generic.fan(31,2): Cannot override non-virtual slot 'generic_0::Algorithm.name'
ERROR: cannot compile script

What fails?

Is there any way to set the Type of function field in subclass of Algorithm?

thanks in advance, Xan

brian Sat 14 Apr 2012

@Xan,

If you just intent your source code at least two spaces it will be preformatted (and a lot easier to read). See Fandoc cheat sheet next to editor.

You cannot override a slot unless the base class declares that slot as virtual. So in your case you need to to change your name slot to something like:

virtual Str name

Xan Sat 14 Apr 2012

I get these errors:

$ fan generic-emulacio.fan 
/home/xan/proves/yot-ng/propi/codi/aranya-fantom/generic-emulacio.fan(32,2): Must specify override keyword to override 'genericemulacio_0::Algorithm.version'
/home/xan/proves/yot-ng/propi/codi/aranya-fantom/generic-emulacio.fan(33,2): Must specify override keyword to override 'genericemulacio_0::Algorithm.function'
/home/xan/proves/yot-ng/propi/codi/aranya-fantom/generic-emulacio.fan(31,2): Must specify override keyword to override 'genericemulacio_0::Algorithm.name'
ERROR: cannot compile script

with

virtual Str name
virtual Int version
virtual |Obj -> Obj| function

in class Algorithm.

brian Sat 14 Apr 2012

I'd suggest reading how virtual methods work in the documentation here. You probably want something like this:

abstract class Algorithm {
  abstract Str name() { "?" }
}

class SizeAlg : Algorithm {
  override Str name() { "Size" }
}

Xan Mon 16 Apr 2012

OK,thanks,

Login or Signup to reply.