Respond to an unknown method call: Difference between revisions

Added FreeBASIC
(→‎{{header|Object Pascal}}: complete replacement of the example)
(Added FreeBASIC)
 
(One intermediate revision by one other user not shown)
Line 364:
x add: \ => "aborted: message not understood"
</syntaxhighlight>
 
=={{header|FreeBASIC}}==
FreeBASIC does not support object-oriented programming, but we can handle the invocation of an undefined method on an object using a data structure such as a dictionary that maps method names to functions. If the method is not defined in the dictionary, you can provide a default response.
<syntaxhighlight lang="vbnet">Type Method
Func As Function() As String
End Type
 
Function DefaultMethod() As String
Return "no such method"
End Function
 
Type Objeto
Methods As Method Ptr
End Type
 
Sub Invoke(obj As Objeto, methodName As String)
If methodName = "exists" Then
Print obj.Methods->Func()
Else
Print DefaultMethod()
End If
End Sub
 
Function exists() As String
Return "exists"
End Function
 
Function CreateObject() As Objeto
Dim As Objeto obj
Dim As Method met
met.Func = @exists
obj.Methods = @met
Return obj
End Function
 
Dim As Objeto o = CreateObject()
Invoke(o, "exists")
Invoke(o, "non_existent_method")
 
Sleep</syntaxhighlight>
{{out}}
<pre>exists
no such method</pre>
 
=={{header|Go}}==
Line 1,656 ⟶ 1,699:
=={{header|Wren}}==
Unlike some other dynamically typed languages, it is not possible to create new methods at runtime in Wren. Attempting to call an unknown method would therefore normally result in a fatal error. However, we can catch such an error and redirect it for user interaction as shown below.
<syntaxhighlight lang="ecmascriptwren">import "io" for Stdin, Stdout
 
class Test {
2,130

edits