Respond to an unknown method call: Difference between revisions

Content added Content deleted
No edit summary
(added Fantom example)
Line 125: Line 125:
a they_can_too: "eat" and: "walk"
a they_can_too: "eat" and: "walk"
</lang>
</lang>

=={{header|Fantom}}==

In Fantom, you can call methods statically or dynamically. Static calls to methods will be checked at compile time. Dynamic method calls (indicated by an <code>instance->method</code> syntax) are run through a "[http://fantom.org/doc/sys/Obj.html#trap trap]" method at run time, and can thus be caught:

<lang fantom>
class A
{
// override the 'trap' method, which catches dynamic invocations of methods
override Obj? trap(Str name, Obj?[]? args := null)
{
echo ("In trap, you called: " + name + " with args " + args.join(","))
return null
}
}

class Main
{
public static Void main ()
{
a := A()
// note the dynamic dispatch
a->methodName (1, 2, 3)
}
}
</lang>

Output:
<pre>
$ fan unknown-method.fan
In trap, you called: methodName with args 1,2,3
</pre>

In normal usage, the trap method tries to locate the named method using reflection on the current class.


=={{header|J}}==
=={{header|J}}==