ch22.md 2.0 KB

Chapter 22. Methods

Methods are the only construct in Nim that uses dynamic dispatch, all other routines use static dispatch. Dynamic dispatch means that the runtime type of objects does influence which operation is performed. For dynamic dispatch to work on an object it should be a reference type. type

Expression = ref object of RootObj ## \
  ## abstract base class for an expression
Literal = ref object of Expression
  x: int
PlusExpr = ref object of Expression
  a, b: Expression

method eval(e: Expression): int {.base.} =

# override this base method
raise newException(CatchableError, "Method without override")

method eval(e: Literal): int = return e.x method eval(e: PlusExpr): int =

# watch out: relies on dynamic binding
result = eval(e.a) + eval(e.b)

proc newLit(x: int): Literal = Literal(x: x) proc newPlus(a, b: Expression): PlusExpr = PlusExpr(a: a, b: b) echo eval(newPlus(newPlus(newLit(1), newLit(2)), newLit(4))) In the example the constructors newLit and newPlus are procs because they should use static binding, but eval is a method because it requires dynamic binding.

                                                                     155

As can be seen in the example, base methods have to be annotated with the base pragma. The base pragma also acts as a reminder for the programmer that a base method m is used as the foundation to determine all the effects that a call to m might cause.

          Generic methods are not supported.
          Compile-time execution is not supported for methods.

22.1. Static method calls via procCall Dynamic method resolution can be inhibited via the builtin system.procCall. This is somewhat comparable to the super keyword that traditional OOP languages offer. type

Thing = ref object of RootObj
Unit = ref object of Thing
   x: int

method m(a: Thing) {.base.} =

echo "base"

method m(a: Unit) =

# Call the base method:
procCall m(Thing(a))
echo "1"